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

如何为Pandas年龄直方图添加'Is True'字段的分组占比图例?

为年龄直方图添加'Is True'占比图例

用到的DataFrame结构

Customer ID年龄Is True
123311
124331
125450
126270
127371
128390
129490
130300
131300
132381

原直方图代码

你之前用来生成年龄直方图的代码:

df.Age.hist()
plt.title('Age')
plt.xlabel('Age')
plt.ylabel('Frequency')

生成的直方图是展示各年龄段样本频次的常规直方图。

实现方法

要给每个年龄区间加上'Is True'=1的样本占比,直接用下面的代码就行:

import matplotlib.pyplot as plt
import pandas as pd

# 初始化你的数据框(如果已经有df可以跳过这部分)
df = pd.DataFrame({
    'Customer ID': [123,124,125,126,127,128,129,130,131,132],
    'Age': [31,33,45,27,37,39,49,30,30,38],
    'Is True': [1,1,0,0,1,0,0,0,0,1]
})

# 绘制直方图,同时拿到区间边界和柱子对象
n, bins, patches = plt.hist(df['Age'], edgecolor='black')
plt.title('年龄分布与Is True占比')
plt.xlabel('年龄')
plt.ylabel('频次')

# 计算每个区间的Is True占比
ratio_list = []
for left, right in zip(bins[:-1], bins[1:]):
    # 筛选当前区间的样本
    interval_samples = df[(df['Age'] >= left) & (df['Age'] < right)]
    if len(interval_samples) == 0:
        ratio = 0
    else:
        # 计算占比:Is True=1的数量/区间总样本数
        ratio = interval_samples['Is True'].sum() / len(interval_samples)
    ratio_list.append(ratio)

# 给每个柱子上方标上占比
for patch, ratio in zip(patches, ratio_list):
    # 拿到柱子的位置和高度,把文本放在柱子正上方
    x_pos = patch.get_x() + patch.get_width() / 2
    y_pos = patch.get_height() + 0.1
    plt.text(x_pos, y_pos, f'{ratio:.1%}', ha='center')

# 添加图例,放在右上角不挡图
plt.legend([f'区间占比: {r:.1%}' for r in ratio_list], bbox_to_anchor=(1.05, 1), loc='upper left')

plt.tight_layout()
plt.show()

关键点说明

  • 用plt.hist()的返回值拿到自动划分的年龄区间,不用手动设置区间
  • 遍历每个区间计算占比,避免手动统计出错
  • 把占比直接标在柱子上方,同时用图例列出所有区间的占比,两种方式结合更清晰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:25:43