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

Viewed 707

I was going over some tutorials including the the official docs and it seems that everyone prefers to Output a figure.

For example:

@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

Why not just outputting only the data to the data field of the figure?

Is it possible?

1 Answers

You can have callbacks that only return the data, and layout and so on

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

But returning Figures is usually less wordy than this, easier to follow, and less error prone

Related