How to update python variables in a callback

I’m new to plotly and dash, and I’m trying to make a simple app to display a figure. I want to be able to press a button and update the data that is being used to generate the graph. I have a small abstraction example present here and my workaround has been to use the global keyword to sync the variables. There must be a better way for me to update the variables in python while callback is executed.

Here is the abstracted code for your reference

from dash import Dash, html, dcc
from dash.dependencies import Input, Output
import random
import plotly.graph_objects as go


x_data = []
y_data = []

app = Dash(__name__)


app.layout = html.Div(
    children=[
        html.H3("Simple Scatter plot from rng data."),
        html.Button("Generate", id="submit-button", n_clicks=0),
        dcc.Graph(id="scatter"),
        html.Div(id="output-div"),
    ]
)


@app.callback(
    Output("scatter", "figure"),
    Input("submit-button", "n_clicks"),
)
def update_output(n_clicks):
    """Display Figure"""
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=x_data, y=y_data, mode="markers"))
    update_values()

    return fig


def update_values():
    """Update data"""
    global x_data, y_data
    x_data.append(random.random())
    y_data.append(random.random())


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

as you can see, x_data and y_data are being appended with new data and callback, which is being used to update the figure being displayed. Thank you for the suggestions!

Hello @harshang and welcome to the forum!

This is really frequent topic on to forum. Firstly check out this part of the official documentation: Part 4. Sharing Data Between Callbacks | Dash for Python Documentation | Plotly

It should give you some overview of this topic. Secondly you will have to to specify the use of the data. Is it small or is it large? What you will use it for? Will this data be somehow updated from some external source? etc

Then we can try to advice you the best solution for you :slight_smile:

1 Like

@martin2097 Thank you! I’ll check out the resource.

The data is being used in the same way as shown here. The data will be generated in the python script, there is no external connection. And it will be appended to the x_data and y_data(one float at a time) at each callback to be displayed. The data will be small at all times.

Yeah but I do not understand the need to save the data into that variable :slight_smile: Check out the resource I sent to you, I believe you will understand why am I asking.