使用pandas从单个列分组另一列来绘制三重条形图

时间:2018-12-30 04:24:37

标签: python pandas

这是我的数据集。

          Country                 Type  Disaster Count
0     CHINA P REP  Industrial Accident             415
1     CHINA P REP   Transport Accident             231
2     CHINA P REP                Flood             175
3           INDIA   Transport Accident             425
4           INDIA                Flood             206
5           INDIA                Storm             121
6   UNITED STATES                Storm             348
7   UNITED STATES   Transport Accident             159
8   UNITED STATES                Flood              92
9     PHILIPPINES                Storm             249
10    PHILIPPINES   Transport Accident              84
11    PHILIPPINES                Flood              71
12      INDONESIA   Transport Accident             136
13      INDONESIA                Flood             110
14      INDONESIA     Seismic Activity              77

我想制作一个三重条形图,标签基于“类型”列。我还想根据“国家”列对酒吧进行分组。

我尝试使用(以df作为熊猫库的DataFrame对象),

df.groupby('Country').plot.bar()

,但结果显示为“国家”列中代表每个组的多个条形图。

预期输出类似于以下内容: Expected output of the graph. Drawn not to scale

要获得此图表,我需要运行哪些代码?

1 个答案:

答案 0 :(得分:1)

有两种方法-

df.set_index('Country').pivot(columns='Type').plot.bar()

enter image description here

df.set_index(['Country','Type']).plot.bar()

enter image description here

相关问题