使用matplotlib子图绘制pandas groupby输出 [英] Plotting pandas groupby output using matplotlib subplots

查看:95
本文介绍了使用matplotlib子图绘制pandas groupby输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a dataframe,df2 which has 6 rows and 1591 columns

           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列的多个绘制为堆叠的条形图.即在单独的面板中绘制的列:0.0.0至1.5.12,在另一面板中绘制的列:3.7.8至1.7.8.这是代码:

I want to plot multiple of 3 columns in each panel in a figure as a stacked bar. that is column: 0.0.0 to 1.5.12 to be plotted in a separate panel and column:3.7.8 to 1.7.8 in another panel. Here is the code:

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:索引器太多

but i get :IndexingError: Too many indexers

推荐答案

初始化子图-

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

接下来,沿第一个轴执行groupby,但尚未绘制.

Next, perform a groupby along the first axis, but don't plot yet.

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

最后,将zip沿轴和groupby的输出向上,并一次绘制每个图.

Finally, zip up the axes and the groupby output, and plot each one at a time.

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

plt.show()

这篇关于使用matplotlib子图绘制pandas groupby输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆