Search code examples
pythonplotlyplotly-dash

Dash share fig object between callbacks


I'd like to use the fig.update_layout method in a callback, my current program looks like this:

app.layout = html.Div([
    dcc.Graph(
        id="sensor-graph",
        config={
            'modeBarButtonsToAdd': [
                "drawrect",
                "eraseshape"
            ]
        },
        style={"display": "none"}
    ),
    html.Button('Occupancy', id="occupancy", n_clicks=0, style={'font-size': '12px', 'width': '140px', 'height':'37px', "background-color": "#7FFFD4"}),
])

and I create the figure for my dcc-graph dynamically in a callback with Output('sensor-graph', 'figure'). I want to be able to label areas with different colors in the sensor-graph with the drawrect functionally dash has. But to change colors when I click the Occupancy Button I need access to the fig attribute to call fig.update_layout, if I just return a new figure the plot will redraw (which is not an option because the graphs take multiple seconds to redraw).
I tried it like this (also changes the button style):

@app.callback(
    [Output("occupancy", "style"), Output("occupancy", "children")],
    Input("occupancy", "n_clicks"),
    [State('sensor-graph', 'figure'), State('occupancy', 'children')]
)
def change_color(_, fig, curr_name):
        fig.update_layout({
            "fillcolor": "green" if curr_name == "No Occupancy" else "red"
        })
        return {"background-color": "#7FFFD4" if curr_name == "No Occupancy" else "#F08080"}, "Occupancy" if curr_name == "No Occupancy" else "No Occupancy"

But I get the following error AttributeError: 'dict' object has no attribute 'update_layout' because Dash returns the figure dict not a go.Figure object with which I could use the update_layout methode.
So my question is: How can I share the go.Figure object between callback functions?


Solution

  • You can reproduce a plotly.graph_objects.Figure from that particular dictionary, you call figure = plotly.graph_objects.Figure(fig) in the callback.