在matplotlib中将y轴标签添加到辅助y轴

时间:2013-02-07 22:22:37

标签: 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('$')

5 个答案:

答案 0 :(得分:160)

最好的方法是直接与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()

example graph

答案 1 :(得分:8)

有一个直接的解决方案,没有搞乱matplotlib:只是pandas。

调整原始示例:

ion-item

基本上,当给出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会返回一个不同的轴,我们用这些轴来设置标签。

我知道很久以前就已经回答了这个问题,但我觉得这种方法很值得。

答案 2 :(得分:6)

我现在无法访问Python,但我不知道如何:

fig = plt.figure()

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

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

答案 3 :(得分:1)

对于每个因熊猫而被绊倒的人, 您现在可以在ax.right_ax

的熊猫中使用directly accessing the secondary_y axis的优雅而简洁的选择

因此,对最初发布的示例进行解释,您将编写:

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

答案 4 :(得分:1)

具有少量 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(...)     # ...
相关问题