Plotly dash: return a simple scatter plot in a callback function

I’m trying to return a scatter plot in a callback function after clicking a button but I have this error: Callback error updating …graph.figure…output.children…

app = Dash(__name__)

app.layout = html.Div([
    html.Button("Plot", id="submit", n_clicks=0),
    dcc.Graph(id='graph')
])

@app.callback(
    Output('graph', 'figure'),
    Input('submit', 'n_clicks'),
)
def update_output(n_clicks):
    return px.scatter(x=[1, 2, 3], y=[2, 6, 7])

if __name__ == '__main__':
    app.run_server(debug=True)

Can anyone please help me to return a simple scatter plot into a callback?

Hi @bryan1 and welcome to the Dash community!

I ran your code without any errors.

image

I think you should have an option that if n_clicks == 0 nothing shows, and when n_clicks > 0, it returns figure:

from dash.exceptions import PreventUpdate
app = Dash(__name__)
app.layout = html.Div([
    html.Button("Plot", id="submit", n_clicks=0),
    dcc.Graph(id='graph',figure={})
])

@app.callback(
    Output('graph', 'figure'),
    Input('submit', 'n_clicks'),
)
def update_output(n_clicks):
    if n_clicks == 0:
        raise PreventUpdate
    elif n_clicks > 0:
        return px.scatter(x=[1, 2, 3], y=[2, 6, 7])

if __name__ == '__main__':
    app.run_server(debug=False,port=1212)