首页 > 解决方案 > 迭代 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'])

但是有效!

我想要一个如下图所示的情节: 在此处输入图像描述

标签: python-3.xpandas

解决方案


下面的代码应该可以完成这项工作:

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)

生产地块 - 3 列

您可以使用seaborn更好的渲染。


推荐阅读