1

After doing groupby in a pandas data-frame I wanna set subplots into different plots stacked next to eachother however, the module puts all of them in one plot

df.groupby('week')['label'].plot(kind='density', legend=True)

enter image description here

Vahid the Great
  • 393
  • 5
  • 18
  • You need to look into using subplots https://stackoverflow.com/questions/31726643/how-do-i-get-multiple-subplots-in-matplotlib – Woody Pride Aug 13 '19 at 18:57
  • Please post data for a [mcve]. See also [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) – Parfait Aug 13 '19 at 19:20

2 Answers2

1

Consider looping through the groupby object and plot to corresponding axes:

import matplotlib.pyplot as plt
...

week_grps = df.groupby('week')
fig, axs = plt.subplots(nrows=1, ncols=len(week_grps), figsize=(15,5))

for ax,(i, sub) in zip(axs, week_grps):
    sub['label'].plot(kind='density', legend=True, title=i, ax=ax)

plt.tight_layout()
plt.show()
plt.clf()
plt.close()
Parfait
  • 104,375
  • 17
  • 94
  • 125
0

I think you want to do

df.groupby('week')['label'].plot(kind='density', legend=True, subplots=True)
Benoit Drogou
  • 969
  • 1
  • 5
  • 15
  • 1
    OP will need to reshape data to wide since [subplots](https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.DataFrame.plot.html) *make separate subplots for each column*. – Parfait Aug 13 '19 at 19:14
  • no. adding subplots=True would just remove the colors but the curves will still remain in one plot. Thanks anyway! – Vahid the Great Aug 13 '19 at 19:15
  • 1
    True sorry about this – Benoit Drogou Aug 13 '19 at 19:16
  • 1
    As mentioned @VahidGhafouri, your data needs to be pivoted to wide format for multiple columns. Try `df.pivot(columns='week', values='label').plot(kind='density', legend=True, subplots=True)` – Parfait Aug 13 '19 at 19:18