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()
2
  • Did you see this post stackoverflow.com/questions/39500265/… ? 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. Commented Jan 17, 2020 at 8:16
  • Your question isn't clear. There is no pd.plot method. Do you want to plot directly from a pd.DataFrame or using plt.plot() as you did in your example? Commented Jan 17, 2020 at 8:39

1 Answer 1

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

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

Comments

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.