You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从groupby数据框选取数据绘制指定国家灾害统计2x2子图

你当前的c_val是双重行索引(MultiIndex)结构,第一层索引为国家名,第二层索引为灾害子类型,所以不能直接按列筛选国家,正确的筛选和绘图方案如下:

方案1:按你原有写法逐个选取(适合固定4个国家的场景)

你之前的loc用法错误,正确的单个国家选取逻辑如下:

import matplotlib.pyplot as plt
import pandas as pd

# 原有预处理代码可先优化,避免rename重复键无效的问题(可选)
# c_val = df_geo.groupby('Country')['Disaster Subtype'].value_counts().reset_index(name='Num of Disaster')

fig, ax = plt.subplots(2,2, figsize=(16,10))

# 选取阿富汗数据
X1 = c_val.loc['Afghanistan'].index
y1 = c_val.loc['Afghanistan', 'Num of Disaster']
ax[0,0].bar(X1,y1,width=.4, color=['#A2BDF2'])
ax[0,0].set_title('Afghanistan')
ax[0,0].tick_params(axis='x', rotation=45) # X轴标签旋转避免重叠

# 选取阿尔巴尼亚数据
X2 = c_val.loc['Albania'].index
y2 = c_val.loc['Albania', 'Num of Disaster']
ax[0,1].bar(X2,y2,width=.4, color=['#A2BDF2'])
ax[0,1].set_title('Albania')
ax[0,1].tick_params(axis='x', rotation=45)

# 选取阿尔及利亚数据
X3 = c_val.loc['Algeria'].index
y3 = c_val.loc['Algeria', 'Num of Disaster']
ax[1,0].bar(X3,y3,width=.4, color=['#A2BDF2'])
ax[1,0].set_title('Algeria')
ax[1,0].tick_params(axis='x', rotation=45)

# 选取美属萨摩亚数据
X4 = c_val.loc['American Samoa'].index
y4 = c_val.loc['American Samoa', 'Num of Disaster']
ax[1,1].bar(X4,y4,width=.4, color=['#A2BDF2'])
ax[1,1].set_title('American Samoa')
ax[1,1].tick_params(axis='x', rotation=45)

plt.tight_layout() # 自动调整子图间距避免标签重叠
plt.show()

方案2:更高效的循环实现(避免重复代码,调整国家只需修改列表)

不需要逐个定义X1-X4、y1-y4,直接遍历目标国家列表和子图即可:

import matplotlib.pyplot as plt
import pandas as pd

# 定义你需要展示的4个国家
target_countries = ['Afghanistan', 'Albania', 'Algeria', 'American Samoa']

fig, axs = plt.subplots(2,2, figsize=(16,10))
# 把2x2的子图数组展平,方便遍历
axs = axs.flatten()

for idx, country in enumerate(target_countries):
    # 直接按第一层索引取对应国家的数据
    country_data = c_val.loc[country]
    x = country_data.index
    y = country_data['Num of Disaster']
    axs[idx].bar(x, y, width=0.4, color='#A2BDF2')
    axs[idx].set_title(country)
    axs[idx].tick_params(axis='x', rotation=45)

plt.tight_layout()
plt.show()

补充说明

如果你更习惯按列筛选的逻辑,可以提前把双重索引转成普通列,筛选逻辑更直观:

# 把MultiIndex转成普通列
c_val_reset = c_val.reset_index()
# 此时筛选阿富汗数据的写法为:
afg_data = c_val_reset[c_val_reset['Country'] == 'Afghanistan']
x = afg_data['Disaster Subtype']
y = afg_data['Num of Disaster']

内容的提问来源于stack exchange,提问作者JamesArthur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 00:06:03