How to create Pandas groupby plot with subplots
Here's an automated layout with lots of groups (of random fake data) and playing around with grouped.get_group(key)
will show you how to do more elegant plots.
import pandas as pdfrom numpy.random import randintimport matplotlib.pyplot as pltdf = pd.DataFrame(randint(0,10,(200,6)),columns=list('abcdef'))grouped = df.groupby('a')rowlength = grouped.ngroups/2 # fix up if odd number of groupsfig, axs = plt.subplots(figsize=(9,4), nrows=2, ncols=rowlength, # fix as above gridspec_kw=dict(hspace=0.4)) # Much control of gridspectargets = zip(grouped.groups.keys(), axs.flatten())for i, (key, ax) in enumerate(targets): ax.plot(grouped.get_group(key)) ax.set_title('a=%d'%key)ax.legend()plt.show()
You could use pd.pivot_table
to get the identifiers
in columns and then call plot()
pd.pivot_table(df.reset_index(), index='index', columns='identifier', values='value' ).plot(subplots=True)
And, the output of
pd.pivot_table(df.reset_index(), index='index', columns='identifier', values='value' )
Looks like -
identifier 55 56 57index2007-01-01 0.781611 0.766152 0.7661522007-02-01 0.705615 0.032134 0.0321342008-01-01 0.026512 0.993124 0.9931242008-02-01 0.226420 0.033860 0.033860