Set legend position when plotting a pandas dataframe with a second y-axis via pandas plotting interface [duplicate]

你说的曾经没有我的故事 提交于 2021-02-10 20:41:40

问题


I am plotting a pandas dataframe with a second y-axis via pandas plotting interface as described in the documentation like this:

df = pd.DataFrame(np.random.randn(24*3, 3),
                  index=pd.date_range('1/1/2019', periods=24*3, freq='h'))
df.columns = ['A (left)', 'B (right)', 'C (right)']
ax = df.plot(secondary_y=['B (right)', 'C (right)'], mark_right=False)
ax.set_ylabel('A scale')
ax.right_ax.set_ylabel('BC scale')
ax.legend(loc='upper right')
plt.show()

which yields As it can be seen, the legend looses entries when I set the position using ax.legend(loc='upper right').

Does anyone know how I can set the legend position and keep all entries?

Thanks in advance!


回答1:


We can use .get_legend_handles_labels() for a more correct solution:

np.random.seed(42)

df = pd.DataFrame(np.random.randn(24*3, 3),
                  index=pd.date_range('1/1/2019', periods=24*3, freq='h'))
df.columns = ['A (left)', 'B (right)', 'C (right)']
ax = df.plot(secondary_y=['B (right)', 'C (right)'], mark_right=False)
ax.set_ylabel('A scale')
ax.right_ax.set_ylabel('BC scale')

h1, l1 = ax.get_legend_handles_labels()
h2, l2 = ax.right_ax.get_legend_handles_labels()
ax.legend(h1+h2, l1+l2, loc=1)

The reason we need to use that method is because ax and ax.right_ax each have their own legend and simply setting them to the same location will render them on top of each other.



来源:https://stackoverflow.com/questions/54090983/set-legend-position-when-plotting-a-pandas-dataframe-with-a-second-y-axis-via-pa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!