0

Given a df of the form

df = pd.DataFrame(
    {
    "date": [datetime.datetime(2018, 1, x) for x in range(1, 8)],    
    "label": ["A", "A", "B", "B", "C", "A", "C"],
    "value1": [1, 22, 3, 4, 5, 6, 7],
    "value2": [10, 4, 30, 5, 6, 8, 9]
    }
)
df.set_index('date', inplace=True)

I'd like to have a single plot that contains all the 6 lines: the value of value1 and value2 for each of the groups. I browsed other answers, but I couldn't find how to properly do it. The best I have is

fig, ax = plt.subplots()
for label, df in grouped:
    df.plot(ax=ax, label="Value for {}".format(label))
plt.legend()

which produces this result:

enter image description here

There are two problems here (prob the same):

  • I can't seem to control the label text
  • the label it is useless as it it now, because it is not informative

Any ideas?

1

1 Answer 1

3

Perhaps just use the axes to plot instead of the DataFrame and explicitly mention what you want to plot?

grouped = df.groupby('label')
fig, ax = plt.subplots()
for label, df2 in grouped:
    ax.plot(df2['value1'], label=label+' value1')
    ax.plot(df2['value2'], label=label+' value2')
plt.xticks(rotation=30)
plt.xlabel(df.index.name)
plt.legend()

enter image description here

Or if you don't want to write that out a lot of times, just specify which columns you want to plot ahead of time, and use another loop.

plot_vals = ['value1', 'value2']

fig, ax = plt.subplots()
for label, df2 in grouped:
    for col in df2.columns[df2.columns.isin(plot_vals)]:
        ax.plot(df2[col], label=label+ ' ' + col)
plt.xticks(rotation=30)
plt.xlabel(df.index.name)
plt.legend()
Sign up to request clarification or add additional context in comments.

3 Comments

for some reason i thought that there is an easier pandas version of everything matplotlib. i might need to start reconsidering this
It's certainly very useful for some things. For instance, using the pandas functionality you don't need to explicitly specify the rotation, or the axis labeling. But matplotlib is always the easiest to fall back on when things don't quite work as you want.
You could use df.pivot(columns='label').interpolate().plot(), however points are expanded and this answer will probably be the best way since the answer mimics your desired plot

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.