Error when trying to produce a Graph in Plotly Dash

Viewed 4598

When trying to produce a figure with the following code

@app.callback(
    [
        Output("selected-plot", "figure")
    ],
    [
        Input("submit-selected-plotting", "n_clicks"),
        State("table", "data")
    ],
)
def plot(button_clicked, data)           
    fig = go.Scatter(x=data["index"],
                     y=data["result"],
                     mode='lines',
                     name='result')
    return fig

and

            dbc.Col(
                [
                    dcc.Graph(id='selected-plot')
                ],
                width=6,
            )

I get a strange error with the app expecting a different object:

dash._grouping.SchemaTypeValidationError: Schema: [<Output selected-plots.figure>] Path: () Expected type: (<class 'tuple'>, <class 'list'>) Received value of type <class 'plotly.graph_objs._scatter.Scatter'>: Scatter({...})

I have tried everything but I can't seem to go around this error. Thanks for any suggestions in advance!

1 Answers

The error is due to the fact that the app expects a figure object, you can fix it by updating the callback as follows:

@app.callback(
    [
        Output("selected-plot", "figure")
    ],
    [
        Input("submit-selected-plotting", "n_clicks"),
        State("table", "data")
    ],
)
def plot(button_clicked, data)     
      
    trace = go.Scatter(
        x=data["index"],
        y=data["result"],
        mode='lines',
        name='result'
    )

    return [go.Figure(data=trace)]
Related