pandas: pandas.DataFrame.plot(): Labels do not appear in legend

The following code plots two lines. The column names appear in the legend.

x=np.linspace(-10,10,201)
y,z=np.sin(x),np.cos(x)
x,y,z=pd.Series(x),pd.Series(y),pd.Series(z)
df=pd.concat([x,y,z],axis=1)
df.columns=['x','sin(x)','cos(x)']
df=df.set_index('x')
df.plot()
plt.show()
plt.clf();plt.close()

figure_1

However, the following equivalent code shows None as legend, even though the labels are explicitly set.

ax=df.plot(y='sin(x)',label='sin(x)')
df.plot(y='cos(x)',label='cos(x)',ax=ax)
plt.show()

Of course there are alternative ways to make this work, but it appears to me that passing the labels should suffice. In particular, I don’t think their values should be replaced with None, or printed as x-label.

figure_2

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 24 (8 by maintainers)

Commits related to this issue

Most upvoted comments

Similar to https://github.com/pandas-dev/pandas/issues/9542#issuecomment-438580042, label is ignored when plotting a one-column DataFrame:

import pandas as pd
df = pd.DataFrame({'a': [2, 3]}, index=[0, 1])
df.plot(label='b')

image

df.plot(label=['b']) also doesn’t work. I’m on 0.25.3.

Having the same issue as previously noted. Using

df[["Training Cost"]].plot(ax=axes[0,0], title = 'Training set', label = 'ADAM')

but the output plot has ‘Training cost’ as the label instead of the specified ‘ADAM’. Wondering what the fix is?

@schmohlio @TomAugspurger I think I have identified this issue causing a regression in legend plotting. Today I upgraded pandas via conda to 0.16.1, and the behaviour of my plotting code changed! Up until now I have been setting labels, without problems, like this (based on @schmohlio 's example above, reduced from the real code as much as possible):

fig, axes = plt.subplots(1, 2)
ax_1 = axes[0]
ax_2= axes[1]
df['sin(x)'].plot(ax=ax_1, label='mylabel_1')
df['cos(x)'].plot(ax=ax_2, label='mylabel_2')
ax_1.legend(loc='best')
ax_2.legend(loc='best')
plt.show()

Expected behaviour: Until now, this plotted the legend entries “mylabel_1” and “mylabel2”, respectively. Observed behaviour: With 0.16.1, the legend entries are “sin (x)” and “cos(x)”. 😦 (tested with an Ipython notebook)

Question 1: Was this an intended change or an unintended regression of this bug? Question 2: (most important) How can I get the old behaviour again? Question 3: Should I report this as a new issue?