Search code examples
pythonplotlyplotly-dashplotly-python

Is there a way to constantly update a graph figure while a switch is on in Dash Plotly Python?


I have a function that updates the figure of a graph using an algorithm, and a callback function to return the graph's figure (among many other things). This is the basic idea:

for i in range(0,5):
    time.sleep(0.1)
    randomfunction(i)
    return plot

How can I update the graph without breaking the loop? I've tried using yield instead of return to no avail as the callback does not expect a generator class to be output.


Solution

  • While the accepted answer certainly works, there is another way to do it for anyone who may want to do this without external storage.

    There is a Dash Core Component called dcc.Interval that you can use to constantly trigger a callback, within which you can update your graph.

    For example, set up a layout that has your graph's layout and the following:

    import dash_core_components as dcc
    dcc.Interval(id="refresh-graph-interval", disabled=False, interval=1000)
    

    Then, in your callback:

    from dash.exceptions import PreventUpdate
    
    @app.callback(
        Output("graph", "figure"), 
        [Input("refresh-graph-interval", "n_intervals")]
    )
    def refresh_graph_interval_callback(n_intervals):
        if n_intervals is not None:
            for i in range(0,5):
                time.sleep(0.1)
                randomfunction(i)
                return plot
        raise PreventUpdate()