如何在Dash应用程序中创建带有平均线的条形图?

2022-04-19 00:00:00 python plotly plotly-dash

问题描述

您好,有人能提供一个如何在Dash中创建带有中线的条形图的代码示例吗?

我设法创建了一个条形图,但我找不到如何通过回调函数输出将跟踪添加到现有的dcc.Graph。

非常感谢。

这是图表外观的示例:

以下是我尝试过的一些代码片段:


    html.Div([
        dcc.Graph(id='surprice_pct_last_month1'),
    ],style={'width': '48%', 'display': 'inline-block'}),


@app.callback(
     dash.dependencies.Output('surprice_pct_last_month2', 'figure'),
    [dash.dependencies.Input('currency2', 'value')])

def update_surprise_last_month2(currency2):

    output = calendar[calendar.Currency == currency2]

    output = output.groupby('Event').last()
    output = output.dropna()
    output1 = output[(output.Surprise_Pct < 400) & (output.Surprise_Pct > -400)]
    output2 = output[(output.Surprise_Pct > 399) | (output.Surprise_Pct < -399)]


    output['Mean'] = output.Surprise_Pct.mean()
    output['Median'] = output.Surprise_Pct.median()
    #output2['Mean'] = output2.Surprise_Pct.mean()
    #output2['Median'] = output2.Surprise_Pct.median()

    data = []
    trace_data = go.Bar(x=list(output.index),
                        y=list(output.Surprise_Pct))
    data.append(trace_data)
    layout = {'title':'Monthly Surprises - {}'.format(currency2)}

    return {
        'data':data,
        'layout': layout
    }


解决方案

这是您需要的吗?

import plotly.graph_objects as go
import random

y = [random.randrange(-200,200) for _ in range(80)]
mean = sum(y) / len(y)
fig = go.Figure([go.Bar(x=list(range(len(y))), y=y)])
fig.add_shape(
        go.layout.Shape(
            type="line",
            x0=-.5,
            y0=mean,
            x1=len(y)-.5,
            y1=mean,
            line=dict(
                color="Orange",
                width=4,
                dash="dash",
            ),
    ))
fig.show()

ps:This online example表示数据只是一个字典列表。因此,为了让Dash发挥作用,我建议:

tracedata1 = go.Bar(x=x, y=y)
tracedata2 = go.layout.Shape(type="line", ...)
data.append(trace_data1)
data.append(trace_data2)

相关文章