Python 在matplotlib中将y轴标签添加到次y轴

Python 在matplotlib中将y轴标签添加到次y轴,python,matplotlib,Python,Matplotlib,我可以使用plt.ylabel将y标签添加到左侧y轴,但如何将其添加到辅助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('$') 最好的方法是直接与轴对象交互 import numpy as np import matplotlib.pyplot

我可以使用
plt.ylabel
将y标签添加到左侧y轴,但如何将其添加到辅助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('$')

最好的方法是直接与
对象交互

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()

我现在没有访问Python的权限,但我想:

fig = plt.figure()

axes1 = fig.add_subplot(111)
# set props for left y-axis here

axes2 = axes1.twinx()   # mirror them
axes2.set_ylabel(...)

有一个简单的解决方案,它不需要修改matplotlib:只需要熊猫

调整原始示例:

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')
基本上,当给出
secondary_y=True
选项时(即使
ax=ax
也被传递)
pandas.plot
返回我们用于设置标签的不同轴


我知道这个问题很久以前就得到了回答,但我认为这种方法是值得的。

对于每个因为提到熊猫而跌跌撞撞地读到这篇文章的人来说, 现在,您可以使用
ax在熊猫中进行非常优雅和严格的选择。右\u ax

因此,解释一下最初发布的示例,您可以这样写:

table = sql.read_frame(query,connection)

ax = table[[0, 1]].plot(ylim=(0,100), secondary_y=table[1])
ax.set_ylabel('$')
ax.right_ax.set_ylabel('Your second Y-Axis Label goes here!')

(这些帖子中也提到了这一点:)

简单的例子,很少有loc:

绘图(y1)
plt.gca().twinx().plot(y2,颜色='r')#默认颜色与第一个ax相同
说明:

ax=plt.gca()#获取当前轴
ax2=ax.twinx()#基于x生成双轴
ax2.绘图(…)#。。。

谢谢-非常好的方法!但是,值得注意的是,仅当您先在主y轴上绘图,然后在次y轴上绘图时,此操作才有效,就像您所做的那样。如果切换顺序,则会出现错误。如何使右y轴与左y轴一样,从下到上,从0到5对齐。如何旋转蓝色文本而不重叠刻度?@Sigur您必须将水平对齐和/或垂直对齐参数传递给ax2.set_ylabel@PaulH,我发现我们可以从ax1获取y限制并将其设置为ax2,这样标签的位置就会对齐。Sigur第一个问题:ax2.set_ylim(ax.get_ylim())Sigur第二个问题:ax2.set_ylabel('Y2 data',rotation=0,labelpad=)希望这对某人有所帮助。这是matplotlib功能,而不是熊猫功能