如何在 Plotly 中为折线图添加 95% 置信区间?

问题描述 投票:0回答:2

我有本福德测试结果,

test_show

    Expected    Counts  Found   Dif AbsDif  Z_score
Sec_Dig                     
0   0.119679    4318    0.080052    -0.039627   0.039627    28.347781
1   0.113890    2323    0.043066    -0.070824   0.070824    51.771489
2   0.108821    1348    0.024991    -0.083831   0.083831    62.513122
3   0.104330    1298    0.024064    -0.080266   0.080266    60.975864
4   0.100308    3060    0.056730    -0.043579   0.043579    33.683738
5   0.096677    6580    0.121987    0.025310    0.025310    19.884178
6   0.093375    10092   0.187097    0.093722    0.093722    74.804141
7   0.090352    9847    0.182555    0.092203    0.092203    74.687841
8   0.087570    8439    0.156452    0.068882    0.068882    56.587749
9   0.084997    6635    0.123007    0.038010    0.038010    31.646817

我正在尝试使用 Plotly 绘制 Benford 结果,如下所示,

这是我到目前为止尝试过的代码

import plotly.graph_objects as go


fig = go.Figure()
fig.add_trace(go.Bar(x=test_show.index,
                y=test_show.Found,
                name='Found',
                marker_color='rgb(55, 83, 109)',
                # color="color"
                ))
fig.add_trace(go.Scatter(x=test_show.index,
                y=test_show.Expected,
                mode='lines+markers',
                name='Expected'
                ))

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()

如何将置信区间添加到

test_show["Expected"]
图中?

python plotly data-visualization
2个回答
6
投票

从 Python 3.8 开始,您可以使用 NormalDist 来计算置信区间,详细说明见此处。通过对该方法稍加调整,您可以使用两条

fig.add_traces()
迹线将其包含在您的设置中,然后为最后一条迹线设置
go.Scatter()
,如下所示:
fill='tonexty', fillcolor = 'rgba(255, 0, 0, 0.2)')

请注意,此方法根据非常有限的 
CI = confidence_interval(df.Expected, 0.95) fig.add_traces([go.Scatter(x = df.index, y = df['Expected']+CI, mode = 'lines', line_color = 'rgba(0,0,0,0)', showlegend = False), go.Scatter(x = df.index, y = df['Expected']-CI, mode = 'lines', line_color = 'rgba(0,0,0,0)', name = '95% confidence interval', fill='tonexty', fillcolor = 'rgba(255, 0, 0, 0.2)')])

系列计算置信区间。这可能不是您想要在这里做的。因此,请让我知道这个初步建议对您有何效果,然后我们就可以从那里采纳。

剧情

完整代码:

df.Expected



0
投票
https://plotly.com/python/continuous-error-bars/

© www.soinside.com 2019 - 2024. All rights reserved.