Black Lives Matter. Please consider donating to Black Girls Code today.

Live update callback error ("not JSON serializable") - Plotly.py and Dash

I’m trying to create a Dash app that has a live-updating graph on it that updates on a set interval. I used some of the code here as a guide, but I’m having issues making mine work.

The page being viewed is:

column1 = dbc.Col(
    [
        dcc.Graph(id='live-update-graph', config={"hideModeBar: True"}),
        dcc.Interval(id='interval-component', interval=10, n_intervals=0)
    ]
)

layout = dbc.Row([column1])


@app.callback(Output('live-update-graph', 'figure'),
              [Input('interval-component', 'n_intervals')])
def update_grid_live(n, grid=None):
    if not grid:
        grid = Grid(25)
        game = create_grid(25, grid)
    else:
        grid.update_grid()
        grid.generation += 1
        game = create_grid(25, grid)
    return game

The function I’m trying to call to create the new graph each time is:


def create_grid(n, grid):
    fig = go.Figure()
    for x in range(n):
        for y in range(n):
            cell = grid.__getitem__(x, y)
            loc_x = [x + 0.5]
            loc_y = [y + 0.5]
            scatter = go.Scatter(x=loc_x, y=loc_y, marker=dict(size=30, symbol=1, color=cell.color), line=dict(width=0),
                                 mode='markers')
            fig.add_trace(scatter)

    fig.update_layout(hovermode="closest", clickmode="event", plot_bgcolor="white", width=1000, height=1000,
                      showlegend=False)
    fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor="black", tickvals=[x for x in range(n)],
                     range=[0, n], scaleanchor="x", constrain="domain", showticklabels=False, ticks="")
    fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor="black", tickvals=[x for x in range(n)],
                     range=[0, n], constrain="domain", scaleanchor="y", showticklabels=False, ticks="")
    return fig

When I run my Dash app, I get an error:

dash.exceptions.InvalidCallbackReturnValue: The callback for property `children` of component `page-content`
returned a value which is not JSON serializable.

In general, Dash properties can only be dash components, strings,
dictionaries, numbers, None, or lists of those.

I think the issue is that the graph I’m returning is type Figure, since if I attempt to just view the JSON for that, it also errors. But the tutorial I was following returns a figure in their callback function. So how do I make mine into a JSON serializable chart?

ETA: grid.update_grid() just changes some of the data being used to create the graph