Andi
Andi

Reputation: 4855

Python: Plot Pandas DataFrame with manually assigned legend

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()

Upvotes: 2

Views: 1251

Answers (1)

gehbiszumeis
gehbiszumeis

Reputation: 3711

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

Upvotes: 4

Related Questions