按级别子图多索引数据

时间:2019-05-16 16:21:00

标签: pandas matplotlib subplot

这是我的多索引数据。

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()

enter image description here

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

2 个答案:

答案 0 :(得分:2)

您可以在pandas

中进行操作
df.Hi.unstack(0).fillna(0).plot(kind='line',subplots=True, layout=(1,2))

enter image description here

答案 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()

enter image description here