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

如何基于pandas DataFrame绘制正确的人口金字塔图表

调整方案

代码异常原因除Age字段为无序字符串外,还缺少人口金字塔核心的数值反转逻辑,具体修改点如下:

  • 修正pandas库的拼写错误(原代码误写为pnadas)
  • 对男性性别的Count值取负,实现左右分栏的金字塔效果
  • 将Age字段设置为有序分类,保证Y轴分组按指定年龄顺序排序
  • 引入matplotlib调整X轴刻度,将左侧负数值显示为正计数,优化可读性

完整可运行代码

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# 原始数据
data = {'Age': ['50-45 years', '50-45 years', '55-65 years', '55-65 years', '65-70 years', '65-70 years'],
        'Gender': ['male', 'female', 'male', 'female', 'male', 'female'], 
        'Count': [4, 5, 6, 7, 11, 12]}
df = pd.DataFrame(data)

# 1. 对男性计数取负,用于左半部分展示
df['Count'] = df.apply(lambda x: -x['Count'] if x['Gender'] == 'male' else x['Count'], axis=1)

# 2. 指定Age分组的顺序,若原始年龄分组存在笔误(如50-45应为45-50)可自行调整该列表
age_order = ['50-45 years', '55-65 years', '65-70 years']
df['Age'] = pd.Categorical(df['Age'], categories=age_order, ordered=True)

# 3. 绘图
plt.figure(figsize=(10, 6))
sns.barplot(data=df, x='Count', y='Age', hue='Gender', orient='h', dodge=False)

# 4. 调整X轴刻度,将负数显示为正数
x_ticks = plt.xticks()[0]
plt.xticks(x_ticks, labels=[str(abs(int(t))) for t in x_ticks])
plt.xlabel('人口数量')
plt.ylabel('年龄分组')
plt.title('人口金字塔')

plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 05:36:04