2

I am trying to manually assign a legend to a plot that is based on a Pandas DataFrame. I thought using the label keyword of the pd.plot function should be the way to go. However, I am struggling...

Here's my toy example:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

# Create dummy dataframe
df = pd.DataFrame(np.random.randint(0, 100, (20, 2)),
                  index=pd.date_range('20190101', periods=20),
                  columns=list('AB'))

# Create plot
fig, ax1 = plt.subplots(1, 1)
ax1.plot(df, label=['line1', 'line2'])
ax1.legend()
Andi
  • 3,196
  • 2
  • 24
  • 44
  • Did you see this post https://stackoverflow.com/questions/39500265/manually-add-legend-items-python-matplotlib ? Otherwise remove the label argument to plot, and pass ax1.legend(df), and you can change the names of the legend by changing the column names. – rich Jan 17 '20 at 08:16
  • Your question isn't clear. There is no `pd.plot` method. Do you want to plot directly from a [`pd.DataFrame`](https://pandas.pydata.org/pandas-docs/stable/user_guide/visualization.html) or using `plt.plot()` as you did in your example? – gehbiszumeis Jan 17 '20 at 08:39

1 Answers1

4

I assume you mean plotting directly from pd.DataFrame. The pd.DataFrame.plot() function returns an matplotlib.axes.Axes object, which you can use to manipulate a legend.

import numpy as np
import pandas as pd

# Create dummy dataframe
df = pd.DataFrame(np.random.randint(0, 100, (20, 2)),
                  index=pd.date_range('20190101', periods=20),
                  columns=list('AB'))

# Create plot directly from pandas.DataFrame
ax = df.plot()
ax.legend(['line1', 'line2'])

gives

enter image description here

gehbiszumeis
  • 3,525
  • 4
  • 24
  • 41