通过pandas绘图界面使用第二个y轴绘制pandas数据框时设置图例位置 [英] Set legend position when plotting a pandas dataframe with a second y-axis via pandas plotting interface

查看:195
本文介绍了通过pandas绘图界面使用第二个y轴绘制pandas数据框时设置图例位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在按照可以看出,当我使用 ax.legend(loc='upper right') 设置位置时,图例会丢失条目.

有人知道我如何设置图例位置并保留所有条目吗?

提前致谢!

解决方案

我们可以使用 .get_legend_handles_labels()获得更正确的解决方案:

np.random.seed(42)df = pd.DataFrame(np.random.randn(24*3, 3),index=pd.date_range('1/1/2019', period=24*3, freq='h'))df.columns = ['A(左)','B(右)','C(右)']ax = df.plot(secondary_y = ['B(右)','C(右)'],mark_right = False)ax.set_ylabel('A标度')ax.right_ax.set_ylabel('BC标度')h1,l1 = ax.get_legend_handles_labels()h2,l2 = ax.right_ax.get_legend_handles_labels()ax.legend(h1+h2, l1+l2, loc=1)

我们之所以需要使用该方法,是因为 ax ax.right_ax 各自都有自己的图例,只需将它们设置在相同的位置即可将其显示在顶部彼此.

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!

解决方案

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.

这篇关于通过pandas绘图界面使用第二个y轴绘制pandas数据框时设置图例位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆