1

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.

2
  • 1
    Did you mean y=[2,3]? If so, the current version of pandas, 0.17, works as expected -- a legend is produced using, for example, df = pd.DataFrame(np.random.random((10,4))), df.plot(x=0, y=[2,3]). Commented Feb 20, 2016 at 22:03
  • Just fixed the typo. Thanks, @unutbu Commented Feb 20, 2016 at 22:42

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.