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

Plotly堆叠直方图:如何按区间内占比展示而非频数?

实现每个区间内占比的堆叠直方图

要实现每个区间(bin)内A_scores和B_scores的占比堆叠直方图,你可以先对数据进行分箱统计,计算每个区间内两类数据的占比,再用堆叠条形图绘制。以下是具体步骤:

步骤1:数据分箱与占比计算

首先用pandas对两列数据统一分箱,确保A、B使用相同的区间,再统计每个箱内的数量并计算占比:

import plotly.express as px
import pandas as pd
import numpy as np

# 原始数据
df = pd.DataFrame({'A_scores':[0.551517,0.534198,0.497253,0.543809,0.543504,0.549244,0.543405,0.558572,0.529337,0.529329,0.534366,0.554673,0.527218,0.543405,0.495575,0.548421,0.500000,0.540934,0.522711,0.578787,0.543405,0.529069,0.555789,0.546029,0.537304,0.542614,0.537506,0.565492,0.540440,0.568631,0.540440,0.529329,0.536587,0.538576,0.528558,0.551652,0.541618,0.553818,0.540803,0.532504,0.542149,0.540440,0.543405,0.539693,0.554483,0.528099,0.544920,0.562185,0.531750,0.539293],
                   'B_scores':[0.541878,0.505649,0.523954,0.540440,0.540440,0.545835,0.540440,0.548533,0.529337,0.529329,0.530605,0.511747,0.542734,0.540440,0.532799,0.537804,0.500000,0.540440,0.540144,0.539606,0.540440,0.543018,0.540440,0.530593,0.529009,0.537180,0.530794,0.556053,0.540440,0.529943,0.540440,0.529329,0.540440,0.541723,0.547892,0.537180,0.534612,0.538470,0.545612,0.508890,0.532759,0.540440,0.540440,0.533806,0.533024,0.521673,0.540440,0.532545,0.513191,0.536977]})

# 统一生成10个区间,确保A、B分箱规则一致
bins = np.histogram_bin_edges(pd.concat([df['A_scores'], df['B_scores']]), bins=10)

# 统计每个区间内A、B的数量
a_counts, _ = np.histogram(df['A_scores'], bins=bins)
b_counts, _ = np.histogram(df['B_scores'], bins=bins)

# 计算每个区间内的占比(处理空区间避免除零)
total_counts = a_counts + b_counts
a_percent = np.where(total_counts == 0, 0, (a_counts / total_counts) * 100)
b_percent = np.where(total_counts == 0, 0, (b_counts / total_counts) * 100)

# 整理为绘图用的DataFrame
bin_labels = [f"{bins[i]:.3f}-{bins[i+1]:.3f}" for i in range(len(bins)-1)]
plot_df = pd.DataFrame({
    '区间': bin_labels,
    'A占比': a_percent,
    'B占比': b_percent
})

步骤2:绘制堆叠条形图

用Plotly Express绘制堆叠条形图,确保每个区间总高度为100%,并保留原始直方图的边框样式:

fig = px.bar(plot_df, x='区间', y=['A占比', 'B占比'], 
             barmode='stack',
             labels={'value': '占比 (%)', 'variable': '类别'})

# 设置边框样式,与原始直方图一致
fig.update_traces(marker_line_color='black', marker_line_width=0.5)

# 调整x轴标签角度,避免重叠
fig.update_layout(xaxis_tickangle=-45)

fig.show()

为什么之前的参数不符合需求?

  • histnorm='percent':将每个区间的频数转换为占总数据的百分比,而非区间内的占比,导致数值错误。
  • barnorm='percent'/barnorm='fraction':Plotly的px.histogram使用这两个参数时,会自动将堆叠模式转为分组模式,破坏了堆叠直方图的样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 13:30:42