Reputation: 3507
If I plot a DataFrame as
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.
Upvotes: 1
Views: 1355
Reputation: 76297
As @unutbu writes, this works well for current versions of Pandas. On older versions, however, I found it easier just to "narrow down" the DataFrame to the relevant columns.
E.g., 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'
:
df[['a', 'b', 'c']].plot(x='a');
This gives you the legend ordering for free.
Upvotes: 1