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

2024-05-16 03:26:52 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的数据集

          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作为pandas库的DataFrame对象)

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

但结果显示,在“国家”一栏中,每个小组都有多个条形图

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

为了实现这个图,我需要运行哪些代码


Tags: df国家countryunitedtransport条形图stormstates
1条回答
网友
1楼 · 发布于 2024-05-16 03:26:52

有两种方法-

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

enter image description here

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

enter image description here

相关问题 更多 >