简体   繁体   中英

How to persist state of plotly graph in Dash App

I have a multi-tab , subtabs dash application. I'd like to be able to save/persist the state of the components in different subtabs when switching between them. These components are dropdown, input, graph, slider, daterange etc.

I use the persistence property of the components which works for input, dropdown, slider but not for Graph. I'd like to persist the state of dcc.Graph component which renders plotly visualization.

dcc.Tabs(

            id="tabs",
            vertical=True,
            persistence=True,

            children=[

                 dcc.Tab(label="Tab 1", value="tab1"),
                 dcc.Tab(label="Tab 2", value="tab2",
                         children=[dcc.Tabs(id="subtabs", 
                                            persistence=True, 
                                          
                            children=[dcc.Tab(label='a', value='ab'),
                                      dcc.Tab(label='z' value='wv')
                                     
                            ],

                    )
                 ]),

            ],
            
        )

Is there a native solution in dash that saves the state of the app? Thx.

I came across this problem when I was developing a dash app. I need to cache figures when switching between different pages. Tweaking storage_type when trying to store them works for me: https://dash.plotly.com/dash-core-components/store

Pseudo code:

@app.callback(
    Output('plt','figure'),
    Input('url','pathname'), # use url to trigger callbacks
    Input('plt,'figure'),
    State('plt-cached','data'),
):
def render_fig(url,plt,plt-cached):
    if url != 'cached_page': raise PreventUpdate
    if not plt: # when switching between pages, dcc.Store('plt') is refreshed when set to 'memory'
        return plt-cached
    # other functions/code to render the plot in your own application

# callback functions to cache figure
@app.callback(
    Output('plt-cached','data'), # dcc.Store('plt-cached') is set to `storage_type=session`
    Input('plt','figure'),
)
def cache_fig(plt):
    return plt

My real application is way more complicated than the above example and the above one might doesn't work if you copy/paste it directly as I didn't even dry-run it. However, you can get the clue to solving your own problem :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM