我想你需要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()
我得到這個錯誤:'KeyError異常。 – user1274878
什麼是'print(df.columns.tolist())'?也許有一些像''date''這樣的空格 – jezrael
那有用,謝謝!還有一件事。你能告訴我如何讓這些情節出現在網格中,而不是一個在另一個之下嗎? – user1274878