如何基于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
相关产品推荐
相关产品推荐

