python-3.x - 迭代 DF 以制作绘图
问题描述
我有 4 列的 da DF:
Date | Year | Month | Production
2010-01-01 2010 1 10
2010-02-01 2010 2 20
2010 ... 30
2010 12 33
2011 1 44
2020 ... ....
column [Date]
是索引。我正在以这种方式绘制图表:
plt.plot(df.index, df['Production'])
我得到了一个从 2010 年到 2020 年的情节。工作得很好。
我想要做的是按年绘制图表,每月像这样:
for year 2010: plot months X Production
for year 2011: plot months X Production
例如,我如何遍历我的 DF 以在每行 3 个图中绘制所有这些图?
我试过了:
years = df['Year'].unique()
for year in years:
plt.plot(years[i], df['Production'])
但是有效!
解决方案
下面的代码应该可以完成这项工作:
nplt = df['Year'].nunique()
ncols = 3
nrows = nplt // ncols + (1 if nplt % ncols else 0)
# Create figure and subplots
fig, axs = plt.subplots(nrows, ncols, sharey=True, sharex=True, figsize=(15, 15))
fig.suptitle('Production')
# Plot one year per subplot
for ax, (year, dfy) in zip(axs.flat, df.groupby('Year')):
ax.set_title(year)
ax.plot(dfy['Month'], dfy['Production'])
# Remove unused subplots
for ax in axs.flat[nplt:]:
fig.delaxes(ax)
您可以使用seaborn
更好的渲染。
推荐阅读
- reactjs - 在 mapStateToProps 中未定义 Redux 状态找不到问题
- reactjs - 我试图在 reatctjs 中建立一个投资组合网站,但我不知道如何解决这些问题,
- python - 如何使用 groupby 制作唯一的用户 ID 级别数据框?
- python - 在 Pandas Python 中将数据框分配给数据框
- ibm-watson - 使用 Postman 测试语音到文本的 watson API,但出现错误 401
- python - 在 pandas 中正确使用 lambda 函数
- arrays - 过滤具有特定属性 Swift 的 json 数组
- vuejs2 - 使用 v-for 过滤数据库中的数据
- mysql - 修复自动增量键 mysql 数据库的顺序
- spring-boot - Spring Security 5 OAuth2 WebClient [client_authorization_required] 客户端注册 ID 所需的授权:假人”