Python 来自单个数据帧的多个绘图
以下是数据框中的字段Python 来自单个数据帧的多个绘图,python,pandas,matplotlib,Python,Pandas,Matplotlib,以下是数据框中的字段 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 ... 我想绘制每个部门的残
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 ...
我想绘制每个部门的残差,日期是x轴,我想单独绘制。我能够为每个部门绘制线条图,但使用以下代码将其作为单个图:
data = pd.DataFrame.from_csv('hardlines_error.csv')
for label, df in data.groupby('dept'):
df.residual.plot( label=label,)
plt.legend()
有人能告诉我如何在网格中以单独的图形绘制它们吗?我认为您需要,如果需要一个图形:
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:索引包含重复的条目,无法重塑
然后需要pivot\u表
或groupby
和聚合函数-检查
但如果需要单独绘制每个图表:
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()
你可以使用Seaborn FaceGrid
当我使用你文章中的最后一段代码时,我收到了这个错误:
keyrerror:'date'
。什么是print(df.columns.tolist())
?也许一些空白,比如“date”
就行了,谢谢!还有一件事。你能告诉我如何使绘图显示在网格中,而不是一个在另一个下面吗?