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

如何用Python(优先Seaborn)绘制分类占比的堆叠百分比直方图

用Seaborn实现分箱年龄的分类占比堆叠百分比直方图

实现步骤

1. 数据预处理:分箱+计算占比

假设你的数据集叫df,包含age(年龄)和category(0/1分类)两列:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# 给年龄分箱,这里默认分5个区间,可自定义bins参数,比如bins=[0,25,50,75,100]
df['age_bin'] = pd.cut(df['age'], bins=5, precision=0)

# 计算每个分箱内0、1分类的占比,转成百分比格式
bin_ratio = df.groupby('age_bin')['category'].value_counts(normalize=True).unstack() * 100
# 补全缺失值(若某分箱仅存在一种分类时)
bin_ratio = bin_ratio.fillna(0)

2. 绘制堆叠百分比图

用Seaborn条形图实现堆叠效果,确保每个分箱总高度为100%:

sns.set_style("whitegrid")
plt.figure(figsize=(10, 6))

# 先绘制分类0的占比,作为堆叠底部
sns.barplot(x=bin_ratio.index, y=bin_ratio[0], color='#1f77b4', label='分类0')
# 绘制分类1的占比,底部对齐分类0的顶部,完成堆叠
sns.barplot(x=bin_ratio.index, y=bin_ratio[1], bottom=bin_ratio[0], color='#ff7f0e', label='分类1')

# 调整图表细节
plt.xlabel('年龄分箱')
plt.ylabel('占比 (%)')
plt.title('各年龄分箱的分类占比分布')
plt.legend(title='分类')
plt.ylim(0, 100)  # 固定y轴范围为0-100%,保证百分比堆叠的直观性
plt.xticks(rotation=45)  # 旋转x轴标签,避免重叠

plt.tight_layout()
plt.show()

自定义调整提示

  • 分箱规则可按需修改:直接给pd.cut传入指定区间列表,比如bins=[18,30,45,60,100]
  • 配色可自行替换:将代码中的颜色值换成偏好的RGB或十六进制码
  • 若追求更接近直方图的连续感,可将分箱设得更细,或调整条形宽度

内容的提问来源于stack exchange,提问作者cogno.luis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 00:55:18