Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib.pyplot: how to include custom legends when plotting dataframes?

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?

like image 338
dabadaba Avatar asked Aug 07 '26 10:08

dabadaba


1 Answers

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.

like image 167
DavidG Avatar answered Aug 08 '26 23:08

DavidG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!