简体   繁体   English

使用y选项时将图例添加到pandas.dataframe.plot

[英]Adding legend to pandas.dataframe.plot when y option is used

If I plot a DataFrame as 如果我将DataFrame绘制为

df.plot()

then each line appears in the legend identifying which column it corresponds to, as it should be. 然后,每一行都会出现在图例中,以标识其对应的列。 However, if I plot it as 但是,如果我将其绘制为

df.plot(x=0, y=[2,3])

then everything is plotted normally, however there is no legend identifying which line is which column. 那么所有内容都会正常绘制,但是没有图例标识哪一行是哪一列。

I have tried 我努力了

df.plot(x=0, y=[2,3], label=['2','3'])
df.plot(x=0, y=[2,3], legend=['2','3'])

but nothing works. 但没有任何效果。 The only workaround is to set 唯一的解决方法是设置

plt.legend(['2','3'])

afterwards, but I am not sure that the order of the legend list is the same order that pandas uses for plotting, so I don't know if the legend really matches the lines. 之后,但我不确定图例列表的顺序是否与熊猫用于绘图的顺序相同,因此我不知道图例是否与线条完全匹配。 Is there a way to make pandas plot the legend is this case? 有没有办法让大熊猫情节传说就是这种情况?

I am using pandas 0.14. 我正在使用熊猫0.14。

As @unutbu writes, this works well for current versions of Pandas. 正如@unutbu所写,这对于当前版本的Pandas效果很好。 On older versions, however, I found it easier just to "narrow down" the DataFrame to the relevant columns. 但是,在较旧的版本上,我发现仅将DataFrame缩小到相关列会更容易。

Eg, suppose you have 例如,假设您有

df = pd.DataFrame({'a': [10, 2], 'b': [2, 3], 'c': [1, 3], 'd': [4, 5]})

Then to plot 'b' and 'c' as a function of 'a' : 然后绘制'b''c'的一个函数'a'

df[['a', 'b', 'c']].plot(x='a');

This gives you the legend ordering for free. 这使您可以免费订购图例。

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

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