按级别子图多索引数据

Subplot multiindex data by level

这是我的多索引数据。

Month   Hour    Hi
1       9       84.39
       10       380.41
       11       539.06
       12       588.70
       13       570.62
       14       507.42
       15       340.42
       16       88.91
2       8       69.31
        9       285.13
       10       474.95
       11       564.42
       12       600.11
       13       614.36
       14       539.79
       15       443.93
       16       251.57
       17       70.51

我想制作子图,其中每个子图代表月份。 x 轴是小时,y 轴是相应月份的 Hi。 This 给出了一个漂亮的方法如下:

levels = df.index.levels[0]
fig, axes = plt.subplots(len(levels), figsize=(3, 25))

for level, ax in zip(levels, axes):
    df.loc[level].plot(ax=ax, title=str(level))
plt.tight_layout()

我想制作 1x2 子图而不是像上面那样垂直排列。后来数据大了,想做3x4的子图,甚至更大的维度。
怎么做?

你可以在 pandas

df.Hi.unstack(0).fillna(0).plot(kind='line',subplots=True, layout=(1,2))

将行和列参数传递给 plt.subplots

levels = df.index.levels[0]
#         Number of rows v
fig, axes = plt.subplots(1, len(levels), figsize=(6, 3))

for level, ax in zip(levels, axes):
    df.loc[level].plot(ax=ax, title=str(level))
plt.tight_layout()