从分组对象堆积条形图

时间:2018-04-26 11:29:01

标签: pandas matplotlib seaborn

我得到了以下分组查询的预期计数。但是当我添加.plot.bar()方法时,我会得到每条记录的条形图。 如何获得堆积条形图?

df.groupby(['department', 'status'])['c_name'].count()

department                                                status  
Agriculture                                               Accepted      3
                                                          Pending       2
                                                          Rejected     13
Department of Education and Training                  Accepted    290
                                                          Rejected     65
Higher Education                                  Accepted    424
                                                          Pending      24
                                                          Rejected     92
Medical Education and Research                    Accepted     34
                                                          Pending       3
                                                          Rejected      1

这将创建条形图,但不会创建堆积条形图。

.plot(kind='bar', stacked=True)

对于每个部门,应该有3种颜色(接受,待定和拒绝)

更新

我使用数据透视管理。

gdf=df.groupby(['department', 'status'])['c_name'].count().reset_index()
gdf.pivot(index='department', columns='status').plot(kind='bar', stacked=True)

但是有可能提高图表质量吗?

1 个答案:

答案 0 :(得分:3)

你很近,需要unstack

df.groupby(['department','status'])['c_name'].count().unstack().plot(kind='bar', stacked=True)

graph