我可以用plt在左y轴上加一个y标签。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('$')
我可以用plt在左y轴上加一个y标签。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('$')
最好的方法是直接与坐标轴对象交互
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也被传递),熊猫。Plot返回我们用来设置标签的不同轴。
我知道这个问题很久以前就有答案了,但我认为这种方法是值得的。
对于每个偶然看到这篇文章的人,因为提到了熊猫, 现在,您可以非常优雅而直接地选择直接访问 用ax.right_ax表示熊猫中的次级y轴
因此,转述最初发布的例子,你可以这样写:
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!')
(这在这些帖子中也已经提到了:1 2)
很少loc的简单示例:
plot(y1)
plt.gca().twinx().plot(y2, color = 'r') # default color is same as first ax
解释:
ax = plt.gca() # Get current axis
ax2 = ax.twinx() # make twin axis based on x
ax2.plot(...) # ...