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

如何基于pandas筛选后的数据绘制各州新冠11月均死亡人数柱状图

实现代码

你可以在现有代码基础上追加如下内容实现需求:

# 先将死亡数据列转换为数值类型,修正此前fillna为字符串的问题,请将下方new_death替换为你数据中实际的死亡数据列名
dflatest['new_death'] = pd.to_numeric(dflatest['new_death'])

# 按州分组计算11月日均死亡数
state_avg_death = dflatest.groupby('state')['new_death'].mean().reset_index()

# 绘制柱状图
plt.figure(figsize=(12, 6))
plt.bar(state_avg_death['state'], state_avg_death['new_death'], color='#4a90e2')

# 配置图表样式
plt.xlabel('州简称', fontsize=12)
plt.ylabel('2020年11月平均每日死亡人数', fontsize=12)
plt.title('各州2020年11月新冠肺炎日均死亡人数对比', fontsize=14)

# 为每个柱子顶部添加数值标注
for state, avg_val in zip(state_avg_death['state'], state_avg_death['new_death']):
    plt.text(state, avg_val + max(state_avg_death['new_death'])*0.01, round(avg_val, 1), ha='center')

plt.grid(axis='y', linestyle='--', alpha=0.6)
plt.tight_layout()
plt.show()

特殊情况处理

如果你数据中存储的是累计死亡人数而非每日新增死亡人数,可先新增每日新增字段再计算均值,追加代码如下:

# 按州、日期排序保证时间顺序正确
dflatest = dflatest.sort_values(by=['state', 'date'])
# 替换cum_death为你数据中实际的累计死亡列名
dflatest['daily_death'] = dflatest.groupby('state')['cum_death'].diff().fillna(0)
# 后续分组统计、绘图逻辑和上述代码完全一致,替换对应列名即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 02:36:04