may
may

Reputation: 1195

How to Groupby and plot it

I have the following dataframe (with different campaigns)

enter image description here

When I use groupby and try to plot, I get several graphs

df.groupby("Campaign").plot(y=["Visits"], x = "Week")

enter image description here

I would like to have only one graph with all the visits in the same graph by every campaign during the week time. Also because the graphs show up separated, I do not know which one belongs to each campaign.

I would appreciate any tips regarding this.

Upvotes: 2

Views: 65

Answers (2)

johnchase
johnchase

Reputation: 13725

Another possible solution would be to use seaborn

import seaborn as sns
ax = sns.lineplot(x="Week",
                  y="Visits",
                  hue="Campaign",
                  estimator=None,
                  lw=1,
                  data=df)

The documentation is here

Upvotes: 2

Scott Boston
Scott Boston

Reputation: 153550

You could do this:

df.set_index(['Week','Campaign'])['Visits'].unstack().plot(title='Visits by Campaign')

For multiple values of Week/Campaign let's aggregate them with sum or you could use mean to average the values:

df.groupby(['Week','Campaign'])['Visits'].sum().unstack().plot(title='Visits by Campain')

Output:

enter image description here

Upvotes: 4

Related Questions