如何为直方图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()
说明:
- 原
data_age_sum的写法不符合Python语法,我们将数据调整为按年龄组顺序排列的列表,保证X轴标签与数据一一对应 - 因为已有统计好的频数,使用
bar绘图比hist更直观;若必须用hist,需将数据展开为原始样本数据,或手动设置bins参数匹配分组 - 通过
ax.text实现分箱顶部的占比标注,确保文本位置居中且不遮挡条形
内容的提问来源于stack exchange,提问作者Lagrange
相关产品推荐
相关产品推荐

