【问题标题】:Plotting pandas groupby output using matplotlib subplots使用 matplotlib 子图绘制 pandas groupby 输出
【发布时间】:2018-06-27 20:10:06
【问题描述】:

我有一个数据框,df2,它有 6 行 1591 列

           0.0.0   10.1.21  1.5.12   3.7.8  3.5.8  1.7.8 ...        
 June       1        1         4      0       0     4
 July       0        0         0      0       0     0
 August     54       0         9      0       5     0
 September  22       0         6      0       0     1
 October    0        9         5      1       4     0

我想将图中每个面板中的 3 列的倍数绘制为堆叠条。即 column: 0.0.0 到 1.5.12 将绘制在单独的面板中,而 column:3.7.8 到 1.7.8 将绘制在另一个面板中。代码如下:

df= df2
df['key1'] = 0
df.key1.loc[:, ['0.0.0', '10.1.21', '1.5.12']].values = 1  
df.key1.loc[:,['3.7.8', '3.5.8', '1.7.8']].values = 2
df.key1.loc[:,['4.4.3', '2.2.0', '2.8.0']].values = 3

# Plot in Three Panels
distinct_keys = df['key1'].unique()
fig, axes = pyplot.subplots(len(distinct_keys), 1, sharex=True, figsize=  (3,5)) 

#{df_subset groups the rows with the same key in other to plot them in the same panel}

for i, key in enumerate(distinct_keys):
df_subset =df[df['key1']==key]

 # plot
axes[i] = df_subset.plot(kind='bar', stacked=True)
pyplot.legend(bbox_to_anchor=(1.04,1), loc="upper right")
pyplot.subplots_adjust(right=0.7)
pyplot.tight_layout(rect=[0,0,0.75,1])
pyplot.savefig("output.png", bbox_inches="tight")

但我得到 :IndexingError: Too many indexers

【问题讨论】:

    标签: python pandas matplotlib plot group-by


    【解决方案1】:

    初始化子图 -

    fig, axs = plt.subplots(len(df.columns) // 3, 1, sharex=True) 
    

    接下来,沿第一个轴执行groupby,但不要绘图。

    gs = df.groupby(np.arange(len(df.columns)) // 3, axis=1)
    

    最后,zip 向上轴和groupby 输出,并一次绘制每一个。

    for (_, g), ax in zip(gs, axs):
         g.plot.bar(stacked=True, ax=ax)
    
    plt.show()
    

    【讨论】:

    • 非常感谢!!!!!!如果没有子图,有没有办法将堆叠条的数量放在特定条的顶部?
    • @Bode 除非我理解错了,否则stacked=True 会自行完成。
    • 不,不是,我的意思是每个条形图顶部的数字表示条形图内堆叠条形的总数
    • @Bode 哦!我明白了……是的……这是一个有趣的问题。我不知道如何解决它!不过,您可以提出一个新问题。
    猜你喜欢
    • 2021-12-27
    • 2015-08-03
    • 1970-01-01
    • 2017-06-13
    • 2017-11-24
    • 2019-04-15
    • 2017-12-12
    • 2018-03-05
    • 2014-07-27
    相关资源
    最近更新 更多