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

Seaborn绘制堆叠直方图时如何为每个分类将Y轴缩放至100%

解决方案

你只需要调整参数并格式化Y轴显示即可实现需求,核心是关闭全局归一化逻辑,让每个X轴分类单独计算堆叠占比:

  1. 第一种方案直接将multiple参数从stack改为fill,该参数会自动将每个X轴分类的堆叠总高度归一化为1(对应100%),再格式化Y轴为百分比展示即可。

修改后的完整代码如下:

import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.ticker import PercentFormatter

fig, axs = plt.subplots(figsize=(5, 5))

sns.histplot(
    df,
    x = "PaperlessBilling",
    hue = "Churn",
    multiple = "fill", # 替换原有stack参数
    stat = "proportion"
)

# 将0~1的比例值转换为百分比格式
axs.yaxis.set_major_formatter(PercentFormatter(1))
axs.set_ylabel("Percent")
# 可按需补充标题、X轴标签、图例样式配置
plt.show()
  1. 如果你希望保留stat="percent"的写法,也可以新增common_norm=False参数关闭全局归一化,实现每个分类单独计算百分比:
fig, axs = plt.subplots(figsize=(5, 5))

sns.histplot(
    df,
    x = "PaperlessBilling",
    hue = "Churn",
    multiple = "stack",
    stat = "percent",
    common_norm = False # 新增参数关闭全局归一化
)
axs.set_ylabel("Percent")
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:54:04