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

如何在Plotly折线图中为Benford测试的Expected值添加95%置信区间

实现方法

步骤1:计算置信区间上下限

95%置信度对应的Z临界值为1.96,比例类指标的置信区间计算公式为:Expected ± 1.96 * sqrt(Expected*(1-Expected)/总样本量)

步骤2:使用Plotly填充层实现阴影效果

通过两条无描边的散点线包裹置信区间范围,设置填充属性即可生成半透明的置信区间阴影。

完整修改后代码

import plotly.graph_objects as go
import numpy as np

# 计算总样本量
N = test_show['Counts'].sum()
# 计算95%置信区间上下限
test_show['ci_upper'] = test_show['Expected'] + 1.96 * np.sqrt(test_show['Expected'] * (1 - test_show['Expected']) / N)
test_show['ci_lower'] = test_show['Expected'] - 1.96 * np.sqrt(test_show['Expected'] * (1 - test_show['Expected']) / N)

fig = go.Figure()
# 新增:95%置信区间阴影层
fig.add_trace(go.Scatter(
    x=test_show.index,
    y=test_show['ci_upper'],
    mode='lines',
    line=dict(width=0),
    showlegend=False
))
fig.add_trace(go.Scatter(
    x=test_show.index,
    y=test_show['ci_lower'],
    mode='lines',
    line=dict(width=0),
    fill='tonexty',
    fillcolor='rgba(128, 177, 211, 0.3)',
    name='95% 置信区间'
))

# 原有柱状图
fig.add_trace(go.Bar(
    x=test_show.index,
    y=test_show.Found,
    name='Found',
    marker_color='rgb(55, 83, 109)'
))
# 原有期望折线
fig.add_trace(go.Scatter(
    x=test_show.index,
    y=test_show.Expected,
    mode='lines+markers',
    name='Expected',
    line=dict(color='rgb(240, 84, 81)', width=2)
))

# 原有布局配置不变
fig.update_layout(
    title='Benfords Law',
    xaxis=dict(
        title='Digits',
        tickmode='linear',
        titlefont_size=16,
        tickfont_size=14),
    yaxis=dict(
        title='% Percentage',
        titlefont_size=16,
        tickfont_size=14,
    ),
    legend=dict(
        x=0,
        y=1.0,
        bgcolor='rgba(255, 255, 255, 0)',
        bordercolor='rgba(255, 255, 255, 0)'
    ))
fig.show()

调整说明

如果需要修改置信区间的样式,调整fillcolor参数即可,RGBA最后一位数值代表透明度,取值范围为0(完全透明)到1(完全不透明)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 03:36:00