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

如何在Python中绘制含概率密度的人口金字塔图?

绘制带概率密度的人口金字塔图(Matplotlib实现)

要实现带概率密度(总面积为1)的人口金字塔图,核心思路是将其中一组的概率密度取负值,绘制在坐标轴左侧,另一组保持正值在右侧,同时确保密度计算的正确性。以下是修改后的完整代码:

import numpy as np
import matplotlib.pyplot as plt

# 模拟数据
X = np.arange(1000)
Y = np.arange(1100)

# 定义分箱
bin_size = 150
bins = np.arange(0, max(max(X), max(Y)) + bin_size, bin_size)

# 计算两组的概率密度
counts_X, bins_X = np.histogram(X, bins=bins, density=True)
counts_Y, bins_Y = np.histogram(Y, bins=bins, density=True)

# 计算分箱中点,用于定位条形图
bin_centers = (bins[:-1] + bins[1:]) / 2
bin_width = np.diff(bins)[0]

# 创建画布与轴
fig, ax = plt.subplots(figsize=(10, 6))

# 绘制左侧组(X,密度取负)
ax.barh(bin_centers, -counts_X, height=bin_width*0.7, color='black', label='X分布')
# 绘制右侧组(Y)
ax.barh(bin_centers, counts_Y, height=bin_width*0.7, color='darkgrey', label='Y分布')

# 设置坐标轴与标签
ax.set_xlabel('概率密度')
ax.set_ylabel('时长 (s)')
ax.set_title('带概率密度的人口金字塔图')

# 调整X轴刻度,显示绝对值(避免左侧显示负数)
x_ticks = ax.get_xticks()
ax.set_xticklabels([f'{abs(tick):.4f}' for tick in x_ticks])

# 保留对数Y轴设置
ax.set_yscale('log')

# 添加图例
ax.legend()

# 优化布局
plt.tight_layout()
plt.show()

关键细节说明:

  • 用np.histogram手动计算概率密度,方便直接控制数值正负,避开hist函数的自动渲染限制
  • 采用barh绘制水平条形图,通过取负实现左右对称的金字塔布局
  • 调整X轴刻度为绝对值,符合人口金字塔的视觉阅读习惯
  • 完整保留了原代码中的对数Y轴设置,适配数据分布特征

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 01:40:06