繁体   English   中英

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

[英]Adding a y-axis label to secondary y-axis in 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('$')

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

示例图

有一个简单的解决方案而不会弄乱 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返回一个不同的轴,我们用来设置标签。

我知道这是很久以前的答案,但我认为这种方法值得。

我现在无法访问 Python,但我的脑海中浮现:

fig = plt.figure()

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

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

对于因为熊猫被提及的绊脚石每个人都在这个岗位,你现在的非常优雅和简单明了的选择直接访问secondary_y轴与大熊猫ax.right_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!')

(这在这些帖子中也已经提到: 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(...)     # ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM