Dash:更新图形的数据而不是更新图形的图形?

Dash: updating a figure's data instead of updating graph's figure?

我正在复习一些教程,包括 official docs,似乎每个人都更喜欢 Outputfigure

例如:

@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 字段?

可能吗?

您可以拥有仅 return 数据和布局等的回调

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}
        }
    }

但是 returning Figures 通常比这更简洁,更容易理解,也更不容易出错