首页 > 解决方案 > 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.

标签: pythonplotly-dashplotly-python

解决方案


我在开发仪表板应用程序时遇到了这个问题。在不同页面之间切换时,我需要缓存数字。尝试存储它们时调整 storage_type 对我有用:https ://dash.plotly.com/dash-core-components/store

伪代码:

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

# 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

我的实际应用程序比上面的示例复杂得多,如果您直接复制/粘贴它,上面的应用程序可能不起作用,因为我什至没有干运行它。但是,您可以获得解决自己问题的线索:)


推荐阅读