python - 在 matplotlib 中更改科学记数法中偏移量的颜色

标签 python colors matplotlib

我正在使用双轴和科学记数法绘制一些曲线。我已经为标签设置了一些颜色,但设置似乎不会影响其轴的科学记数法的功率指示器。有什么技巧吗?

Example

这是我的代码:

fig = pylab.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()

# Plotting the data
plot_ax1, = ax1.plot()
plot_ax2, = ax2.plot()

# Setting the label colors
ax2.yaxis.set_offset_position('right') # To set the power indicator of ax2 
ax1.yaxis.label.set_color(plot_ax1.get_color())
ax2.yaxis.label.set_color(plot_ax2.get_color())

# Setting the ticker properties     
tkw = dict(size=4, width=1.5)
ax1.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
ax2.ticklabel_format(style='sci', scilimits=(0,0), axis='y')        
ax1.tick_params(axis='y', colors=plot_ax1.get_color(), **tkw)
ax2.tick_params(axis='y', colors=plot_ax2.get_color(), **tkw)
ax1.tick_params(axis='x', **tkw)

# Setting the legend
lines = [plot_ax1, plot_ax2]
ax1.legend(lines, [l.get_label() for l in lines],'upper left')

最佳答案

这可能只是一个疏忽,tick_params 还没有这样做,但您可以简单地手动设置它。

例如,只需将这两行添加到您的示例代码中:

ax1.yaxis.get_offset_text().set_color(plot_ax1.get_color())
ax2.yaxis.get_offset_text().set_color(plot_ax2.get_color())

作为一个更完整的示例,使用上面的代码片段和一些随机数据:

import matplotlib.pyplot as plt
import numpy as np

numdata = 100
t = np.linspace(0.05, 0.11, numdata)
x1 = np.cumsum(np.random.random(numdata) - 0.5) * 40000
x2 = np.cumsum(np.random.random(numdata) - 0.5) * 0.002

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()

# Plotting the data
plot_ax1, = ax1.plot(t, x1, 'r-', label='x1')
plot_ax2, = ax2.plot(t, x2, 'g-', label='x2')

# Setting the label colors
ax2.yaxis.set_offset_position('right') # To set the power indicator of ax2 
ax1.yaxis.label.set_color(plot_ax1.get_color())
ax2.yaxis.label.set_color(plot_ax2.get_color())

# Setting the ticker properties     
tkw = dict(size=4, width=1.5)
ax1.ticklabel_format(style='sci', scilimits=(0,0), axis='y')
ax2.ticklabel_format(style='sci', scilimits=(0,0), axis='y')        
ax1.tick_params(axis='y', colors=plot_ax1.get_color(), **tkw)
ax2.tick_params(axis='y', colors=plot_ax2.get_color(), **tkw)

ax1.yaxis.get_offset_text().set_color(plot_ax1.get_color())
ax2.yaxis.get_offset_text().set_color(plot_ax2.get_color())

ax1.tick_params(axis='x', **tkw)

# Setting the legend
lines = [plot_ax1, plot_ax2]
ax1.legend(lines, [l.get_label() for l in lines],'upper left')

plt.show()

enter image description here

关于python - 在 matplotlib 中更改科学记数法中偏移量的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4991178/

相关文章:

python - 我应该使用 Perl 还是 Python 进行网络监控?

python - 在 Python 中将多个变量值分配给单个变量

python - 使用命令行 waitress-serve 进行日志记录

python - 如何从安然电子邮件正文中删除 "forwarded message"标题和不需要的内容?

php - 使用 PHP 生成随机颜色

更改 OS X 控制台输出中的颜色

r - kableExtra - 条纹颜色

python - 在python中显示二进制文件中的数据

python - matplotlib 小部件中的离散 slider

python - 在 matplotlib 中绘制 10 负幂的 xscale