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!