2015-04-30 14 views
6

Ho un frame di dati come questo:Come si può creare un gruppo di Pandas tramite la trama secondaria?

 value  identifier 
2007-01-01 0.781611  55 
2007-01-01 0.766152  56 
2007-01-01 0.766152  57 
2007-02-01 0.705615  55 
2007-02-01 0.032134  56 
2007-02-01 0.032134  57 
2008-01-01 0.026512  55 
2008-01-01 0.993124  56 
2008-01-01 0.993124  57 
2008-02-01 0.226420  55 
2008-02-01 0.033860  56 
2008-02-01 0.033860  57 

così faccio un groupby per identificatore:

df.groupby('identifier') 

e ora voglio generare sottotrame in una griglia, una trama per gruppo. Ho provato entrambi

df.groupby('identifier').plot(subplots=True) 

o

df.groupby('identifier').plot(subplots=False) 

e

plt.subplots(3,3) 
df.groupby('identifier').plot(subplots=True) 

inutilmente. Come posso creare i grafici?

+0

check-out 'seaborn', lo fa davvero bene. – cphlewis

+0

Grazie, ma sto cercando di evitare seaborn e utilizzare solo matplotlib. Dipendenze e ambiente Windows, ecc. – Ivan

risposta

5

Ecco un layout automatizzato con molti gruppi (di dati falsi casuali) e giocare con grouped.get_group(key) ti mostrerà come realizzare trame più eleganti.

import pandas as pd 
from numpy.random import randint 
import matplotlib.pyplot as plt 


df = pd.DataFrame(randint(0,10,(200,6)),columns=list('abcdef')) 
grouped = df.groupby('a') 
rowlength = grouped.ngroups/2       # fix up if odd number of groups 
fig, axs = plt.subplots(figsize=(9,4), 
         nrows=2, ncols=rowlength,  # fix as above 
         gridspec_kw=dict(hspace=0.4)) # Much control of gridspec 

targets = 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() 

enter image description here

+0

Hai menzionato la correzione se dispari, quindi: rowlength = grouped.ngroups/2 + (0 se grouped.ngroups% 2 == 0 else 1) –

+0

È utile capire che la ragione per cui funziona è che generi un gruppo di assi e passi ciascun oggetto asse a turno a ciascun gruppo che viene tracciato. Riempi ogni sottofigura con una trama di sottogruppi. Neat! –

6

si utilizza pivot per ottenere il identifiers in colonne e poi tracciare

pd.pivot_table(df.reset_index(), 
       index='index', columns='identifier', values='value' 
      ).plot(subplots=True) 

enter image description here

E, l'uscita del

pd.pivot_table(df.reset_index(), 
       index='index', columns='identifier', values='value' 
       ) 

Sembra -

identifier  55  56  57 
index 
2007-01-01 0.781611 0.766152 0.766152 
2007-02-01 0.705615 0.032134 0.032134 
2008-01-01 0.026512 0.993124 0.993124 
2008-02-01 0.226420 0.033860 0.033860 
Problemi correlati