3

I am plotting two dataframes in the same chart: the USDEUR exchange rate and the 3-day moving average.

df.plot(ax=ax, linewidth=1)
rolling_mean.plot(ax=ax, linewidth=1)

Both dataframes are labelled "Value" so I would like to customize that:

enter image description here

I tried passing the label option but that didn't work, as it seems that this option is exclusive to matplotlib.axes.Axes.plot and not to pandas.DataFrame.plot. So I tried using axes instead, and passing each label:

ax.plot(df, linewidth=1, label='FRED/DEXUSEU')
ax.plot(rolling_mean, linewidth=1, label='3-day SMA')

However now the legend is not showing up at all unless I explicitly call ax.legend() afterwards.

Is it possible to plot the dataframes while passing custom labels without the need of an additional explicit call?

1 Answer 1

4

When setting a label using df.plot() you have to specifiy the data which is being plotted:

fig, (ax1, ax2) = plt.subplots(1,2)

df = pd.DataFrame({'Value':np.random.randn(10)})
df2 = pd.DataFrame({'Value':np.random.randn(10)})

df.plot(label="Test",ax=ax1)
df2.plot(ax=ax1)

df.plot(y="Value", label="Test",ax=ax2)
df2.plot(y="Value", ax=ax2)

ax1.set_title("Reproduce problem")
ax2.set_title("Possible solution")

plt.show()

Which gives:

enter image description here

Update: It appears that there is a difference between plotting a dataframe, and plotting a series. When plotting a dataframe, the labels are taken from the column names. However, when specifying y="Value" you are then plotting a series, which then actually uses the label argument.

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

2 Comments

Pretty weird that explicitly indicating the column to be plotted triggers the legend, but it does work. I guess it will make sense the more I use these libraries.
@dabadaba I've updated my answer with a bit more of an explanation as to why this happens

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.