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

如何为直方图X轴分箱添加标签并显示对应人员占比?

解决方案

先修正原数据的Python语法错误,再按需求调整绘图代码,实现X轴分箱标签设置和占比显示:

import matplotlib.pyplot as plt

# 按年龄组编码1-7的顺序整理标签与对应频数
age_labels = ['<18', '18-24', '25-34', '35-44', '45-54', '55-60', '>60']
counts = [3, 193, 126, 16, 6, 1, 0]

# 计算总人数与各组占比
total = sum(counts)
percentages = [f'{(cnt/total)*100:.1f}%' if total else '0%' for cnt in counts]

# 绘制柱状图(适配已统计好的频数,比hist更合适)
fig, ax = plt.subplots()
bars = ax.bar(range(len(age_labels)), counts)

# 设置X轴分箱标签
ax.set_xticks(range(len(age_labels)))
ax.set_xticklabels(age_labels)

# 在每个分箱顶部添加占比文本
for bar, pct in zip(bars, percentages):
    ax.text(bar.get_x() + bar.get_width()/2, bar.get_height(),
            pct, ha='center', va='bottom')

# 配置图表信息
ax.set_xlabel('年龄组')
ax.set_ylabel('人数')
plt.title('您属于哪个年龄组?')
plt.show()

说明:

  1. 原data_age_sum的写法不符合Python语法,我们将数据调整为按年龄组顺序排列的列表,保证X轴标签与数据一一对应
  2. 因为已有统计好的频数,使用bar绘图比hist更直观;若必须用hist,需将数据展开为原始样本数据,或手动设置bins参数匹配分组
  3. 通过ax.text实现分箱顶部的占比标注,确保文本位置居中且不遮挡条形

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 04:05:27