[英]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!')
幾個 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.