破折号:更新图形的数据而不是更新图形的图形?

2024-09-28 01:32:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我看了一些教程,包括official docs,似乎每个人都喜欢Outputafigure

例如:

@app.callback(
    Output('graph-with-slider', 'figure'),
    Input('year-slider', 'value'))
def update_figure(selected_year):
    filtered_df = df[df.year == selected_year]

    fig = px.scatter(filtered_df, x="gdpPercap", y="lifeExp",
                     size="pop", color="continent", hover_name="country",
                     log_x=True, size_max=55)

    fig.update_layout(transition_duration=500)

    return fig

为什么不只是将数据输出到图的data字段

可能吗


Tags: appdocsdfsizecallbackfigupdate教程
1条回答
网友
1楼 · 发布于 2024-09-28 01:32:55

您可以使用只返回数据、布局等的回调

app.layout = html.Div([
    dcc.Dropdown(
        id='my_input',
        value='A',
        options=[{'label': i, 'value': i} for i in ["value_1","value_2"]]
    ),
    dcc.Graph(id='my_graph')
])


@app.callback(Output('my_graph', 'figure'),
              Input('my_input', 'value'))
def update_live_graph(value):
    data = get_data() #assuming dataframe/dict for simplicity
    return {
        'data': [{
            'x': data['x'],
            'y': data['y'],
            'line': {...} # line properties, could also be marker={...}
        }],
        'layout': {
            # aesthetic options
            'margin': {'l': 40, 'b': 40, 'r': 20, 't': 10},
            'xaxis': {'showgrid': False, 'zeroline': False},
            'yaxis': {'showgrid': False, 'zeroline': False}
        }
    }

但返回的数据通常没有这样冗长,更容易理解,也不容易出错

相关问题 更多 >

    热门问题