2017-06-23 132 views
1

下面是我要繪製的殘差的日期爲x軸的各個部門在數據幀多條曲線數據幀

date  dept  residual 
4/22/17  8   100.00 
4/29/17  8   23.34 
....  8   ... 
....  8   ... 

4/22/17  12   10.10 
....  12   ... 
....  12   ... 

的領域,我想單獨地塊。我能夠繪製線圖的每個部門,但作爲一個單一的情節使用下面的代碼:

data = pd.DataFrame.from_csv('hardlines_error.csv') 

for label, df in data.groupby('dept'): 
    df.residual.plot( label=label,) 
plt.legend() 

有人能告訴我如何將它們繪製在網格獨立的情節?

回答

2

我想你需要pivot然後plot如果需要一個圖表:

df = df.pivot(index='date',columns='dept', values='residual') 
print (df) 
dept   8  12 
date     
4/22/17 100.00 10.1 
4/29/17 23.34 NaN 

替代解決方案:

df = df.set_index(['date','dept'])['residual'].unstack() 
print (df) 
dept   8  12 
date     
4/22/17 100.00 10.1 
4/29/17 23.34 NaN 


df.plot() 

但是,如果有重複,得到錯誤:

ValueError: Index contains duplicate entries, cannot reshape

那麼需要pivot_table或帶聚合功能的3210 - 檢查this answer

但如果需要單獨的每個圖:

for i, group in df.groupby('dept'): 
    plt.figure() 
    group.plot(x='date', y='residual', title=str(i)) 

對於網格使用:

import matplotlib.pyplot as plt 

grouped = df.groupby('dept') 

ncols=2 
nrows = int(np.ceil(grouped.ngroups/ncols)) 

fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,4), sharey=True) 
for (key, ax) in zip(grouped.groups.keys(), axes.flatten()): 
    grouped.get_group(key).plot(x='date', y='residual', ax=ax) 

ax.legend() 
plt.show() 
+0

我得到這個錯誤:'KeyError異常。 – user1274878

+0

什麼是'print(df.columns.tolist())'?也許有一些像''date''這樣的空格 – jezrael

+0

那有用,謝謝!還有一件事。你能告訴我如何讓這些情節出現在網格中,而不是一個在另一個之下嗎? – user1274878