Python 将 y 轴标签添加到 matplotlib 中的辅助 y 轴
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14762181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding a y-axis label to secondary y-axis in matplotlib
提问by Osmond Bishop
I can add a y label to the left y-axis using plt.ylabel, but how can I add it to the secondary y-axis?
我可以使用 将 y 标签添加到左侧 y 轴plt.ylabel,但如何将其添加到辅助 y 轴?
table = sql.read_frame(query,connection)
table[0].plot(color=colors[0],ylim=(0,100))
table[1].plot(secondary_y=True,color=colors[1])
plt.ylabel('$')
采纳答案by Paul H
The best way is to interact with the axesobject directly
最好的方式是axes直接与对象交互
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 10, 0.1)
y1 = 0.05 * x**2
y2 = -1 *y1
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b-')
ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')
ax2.set_ylabel('Y2 data', color='b')
plt.show()


回答by Micke
I don't have access to Python right now, but off the top of my head:
我现在无法访问 Python,但我的脑海中浮现:
fig = plt.figure()
axes1 = fig.add_subplot(111)
# set props for left y-axis here
axes2 = axes1.twinx() # mirror them
axes2.set_ylabel(...)
回答by kiril
There is a straightforward solution without messing with matplotlib: just pandas.
有一个简单的解决方案而不会弄乱 matplotlib:只是熊猫。
Tweaking the original example:
调整原始示例:
table = sql.read_frame(query,connection)
ax = table[0].plot(color=colors[0],ylim=(0,100))
ax2 = table[1].plot(secondary_y=True,color=colors[1], ax=ax)
ax.set_ylabel('Left axes label')
ax2.set_ylabel('Right axes label')
Basically, when the secondary_y=Trueoption is given (eventhough ax=axis passed too) pandas.plotreturns a different axes which we use to set the labels.
基本上,当secondary_y=True给出选项时(尽管也ax=ax被传递)pandas.plot返回一个不同的轴,我们用来设置标签。
I know this was answered long ago, but I think this approach worths it.
我知道这是很久以前的答案,但我认为这种方法值得。

