Python 中的人口金字塔图:分析 2023 年按年龄分列的死亡数据

인구 피라미드 그래프 형식의 남녀 연령별 사망주 수 이미지
(按性别和年龄分列的死亡人数图片(人口金字塔图)

在可视化人口数据时,添加数据标签可以大大提高信息的准确性和可读性。今天,我们将学习如何在人口金字塔图中加入数据标签,以可视化 2023 年各年龄段的死亡人数。

数据概览

上述 Python 可视化图表的基础数据来自 24 年 2 月发布的 2023 年出生和死亡统计数据(暂定)死亡人数。以下是该数据的表格,死亡人数以千为单位。

年龄组男性死亡人数女性死亡人数
90+15.342.1
80-8963.569.6
70-7945.524.6
60-6934.313.2
50-5918.07.2
40-497.03.8
30-392.81.5
20-291.70.9
10-190.40.4
1-90.20.1
0-0.30.3

남녀 연령별 사망자 수 기반 인구 피라미드 그래프 이미지
(人口金字塔图摘自 Statista)

让我们将上表中按年龄划分的 2023 年死亡人数数据绘制成人口金字塔图,并标注出每个年龄组的确切数字,以提供更多细节。

执行 Python 可视化代码

将 numpy 导入 np
import matplotlib.pyplot as plt

准备 # 数据
age_groups = ['90+', '80-89', '70-79', '60-69', '50-59', '40-49'、
              '30-39', '20-29', '10-19', '1-9', '0-']
男性死亡人数 = [15.3, 63.5, 45.5, 34.3, 18.0, 7.0, 2.8, 1.7, 0.4, 0.2, 0.3]
女性死亡人数 = [42.1, 69.6, 24.6, 13.2, 7.2, 3.8, 1.5, 0.9, 0.4, 0.1, 0.3]

使用 # GridSpec 生成图形
fig = plt.figure(figsize=(15, 8))
gs = fig.add_gridspec(1, 3, width_ratios=[4, 0.01, 4]) # 设置中心列的比率为 0.01

# 创建三个子图
ax_left = fig.add_subplot(gs[0])
ax_center = fig.add_subplot(gs[1])
ax_right = fig.add_subplot(gs[2])

y_pos = np.array(len(age_groups))

# 左图(男性)
male_bars = ax_left.barh(y_pos, -np.array(male_deaths), align='center'、
                        color='#5AB1EF', height=0.7)

# 右图(女性)
female_bars = ax_right.barh(y_pos, female_deaths, align='center'、
                           color='#FFB848', height=0.7)

添加 # 数据标签
def add_labels(ax, bars):
    for bar in bars:
        width = bar.get_width()
        x = 宽度
        value = abs(width)
        ax.text(x, bar.get_y() + bar.get_height()/2, f'{value}'、
                ha='right' if width < 0 else 'left'、
                va='居中'、
                fontsize=9、
                fontweight='bold'、
                color='黑色'、
                bbox=dict(pad=0.4, facecolor='none', edgecolor='none'))

add_labels(ax_left, male_bars)
add_labels(ax_right, female_bars)

# 中心图(年龄组)
ax_center.set_yticks(y_pos)
ax_center.tick_params(axis='y', length=0)
# 年龄标签居中对齐
ax_center.set_yticklabels(age_groups, ha='center')

设置 # 居中列的样式
ax_center.set_xlim(-0.5, 0.5) # 缩小 x 轴范围,使标签更居中
ax_center.set_xticks([])
for spine in ax_center.spines.values():
    spine.set_visible(False)

# 设置左右绘图的样式
for ax in [ax_left, ax_right]:
    ax.grid(axis='x', linestyle='-', alpha=0.1)
    ax.set_yticks([])
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    
设置 # x 轴范围
max_value = max(max(男性死亡人数), max(女性死亡人数))
ax_left.set_xlim(-max_value*1.1, 0)
ax_right.set_xlim(0, max_value*1.1)

为 # 轴添加标签
ax_left.set_xlabel('Number of Deaths (000)',ha='right')
ax_right.set_xlabel('Number of Deaths (thousands)', ha='left')

添加 # 男性/女性标签
ax_left.text(-max_value/2, len(age_groups), 'Male', ha='center', va='bottom', fontsize=12)
ax_right.text(max_value/2, len(age_groups), 'Female', ha='center', va='bottom', fontsize=12)

设置 # x 轴刻度线格式
def format_ticks(x, p):
    return f'{abs(x)}'
ax_left.xaxis.set_major_formatter(plt.FuncFormatter(format_ticks))
ax_right.xaxis.set_major_formatter(plt.FuncFormatter(format_ticks))

为 # 图表添加标题
fig.suptitle('Age-Specific Mortality by Gender', y=0.95, fontsize=14)

plt.tight_layout()
plt.subplots_adjust(top=0.9) # 调整标题页边距
plt.show()

深入的数据分析见解

1. 按年龄组划分的死亡率差异

    • 80-89 岁年龄组:男性(63.5 千米)和女性(69.6 千米)达到峰值
    • 70 岁以下男性的总体死亡率较高
    • 观察随着年龄增长性别差距模式的变化

    2. 生命周期功能

      • 婴儿期(0 岁):男童和女童死亡率相同 (0.3k)
      • 青壮年(20-49 岁):男性死亡率约为女性的两倍
      • 老年人(80 岁及以上):女性死亡率飙升

      3. 政策影响

        • 需要制定针对不同性别和年龄的医疗保健政策
        • 呼吁为老年妇女提供更多保健服务
        • 加强预防保健,降低中年男性死亡率

        总结

        带有数据标签的人口金字塔图可以让您直观地了解各年龄段的确切死亡人数。这种可视化可作为人口分析和医疗保健政策制定的重要依据。详细代码注释见下文。

        如果您想了解与死亡人数相反的总和生育率,可以使用 总和生育率的定义和计算:用 R 进行趋势可视化分析 帖子,了解更多信息。

        # 代码说明

        1. 导入所需的库
        将 numpy 导入 np
        import matplotlib.pyplot as plt
        • numpy数值计算库
        • matplotlib.pyplot:图形生成库
        2. 准备数据
        age_groups = ['90+', '80-89', '70-79', '60-69', '50-59', '40-49'、
                      '30-39', '20-29', '10-19', '1-9', '0-']
        男性死亡人数 = [15.3, 63.5, 45.5, 34.3, 18.0, 7.0, 2.8, 1.7, 0.4, 0.2, 0.3]
        女性死亡 = [42.1, 69.6, 24.6, 13.2, 7.2, 3.8, 1.5, 0.9, 0.4, 0.1, 0.3]

        以列表形式定义每个年龄组和每个性别的死亡人数数据。

        3.设置图形结构
        fig = plt.figure(figsize=(15, 8))
        gs = fig.add_gridspec(1, 3, width_ratios=[4, 0.01, 4])
        • figsize=(15, 8):设置图表的整体大小(水平 15,垂直 8)
        • 添加网格规范:将图形分成三列。将比例设为 [4, 0.01, 4],使中间一列非常窄。
        4.创建分镜头
        ax_left = fig.add_subplot(gs[0])
        ax_center = fig.add_subplot(gs[1])
        ax_right = fig.add_subplot(gs[2])

        创建三个子图块(左、中、右)。

        5. 绘制条形图
        y_pos = np.array(len(age_groups))
        
        male_bars = ax_left.barh(y_pos, -np.array(male_deaths), align='center'、
                                color='#5AB1EF', height=0.7)
        female_bars = ax_right.barh(y_pos, female_deaths, align='center'、
                                   color='#FFB848', height=0.7)
        • 酒吧:绘制水平条形图的函数
        • 将男性数据转换为负数并显示在左侧
        • 右侧为女性数据
        6. 添加数据标签
        def add_labels(ax, bars):
            for bar in bars:
                width = bar.get_width()
                x = 宽度
                value = abs(width)
                ax.text(x, bar.get_y() + bar.get_height()/2, f'{value}'、
                        ha='right' if width < 0 else 'left'、
                        va='居中'、
                        fontsize=9、
                        fontweight='bold'、
                        color='黑色'、
                        bbox=dict(pad=0.4, facecolor='none', edgecolor='none'))
        
        add_labels(ax_left, male_bars)
        add_labels(ax_right, female_bars)

        为每个条形添加相应的数字作为标签。

        7. 设置中心栏样式
        ax_center.set_yticks(y_pos)
        ax_center.tick_params(axis='y', length=0)
        ax_center.set_yticklabels(age_groups, ha='center')
        ax_center.set_xlim(-0.5, 0.5)
        ax_center.set_xticks([])
        for spine in ax_center.spines.values():
            spine.set_visible(False)

        在中心栏显示年龄组标签,删除不必要的坐标轴和边框。

        8. 设置左右绘图的样式
        for ax in [ax_left, ax_right]:
            ax.grid(axis='x', linestyle='-', alpha=0.1)
            ax.set_yticks([])
            ax.spines['top'].set_visible(False)
            ax.spines['right'].set_visible(False)

        为左右绘图添加网格,删除不必要的坐标轴。

        9.设置 X 轴范围并添加标签
        max_value = max(max(男性死亡人数), max(女性死亡人数))
        ax_left.set_xlim(-max_value*1.1, 0)
        ax_right.set_xlim(0, max_value*1.1)
        
        ax_left.set_xlabel('Number of Deaths (000)',ha='right')
        ax_right.set_xlabel('Number of Deaths (000)',ha='left')
        
        ax_left.text(-max_value/2, len(age_groups), 'Male', ha='center', va='bottom', fontsize=12)
        ax_right.text(max_value/2, len(age_groups), 'Female', ha='center', va='bottom', fontsize=12)

        设置 x 轴的范围,添加轴标签和性别标签。

        10.设置 X 轴刻度格式
        def format_ticks(x, p):
            return f'{abs(x)}'
        ax_left.xaxis.set_major_formatter(plt.FuncFormatter(format_ticks))
        ax_right.xaxis.set_major_formatter(plt.FuncFormatter(format_ticks))

        以绝对值显示 x 轴刻度上的数值。

        11.最后确定图表
        fig.suptitle('Age-Specific Mortality by Gender', y=0.95, fontsize=14)
        plt.tight_layout()
        plt.subplots_adjust(top=0.9)
        plt.show()

        为图表添加标题、调整布局并显示图表。

        类似文章