I’m considering moving an app from R shiny to Dash, but I’m having trouble getting sliders and menus to interact while remembering their values, mostly because I keep encountering circular dependencies. I think that this probably has a simple, elegant solution, but it eludes me. On the other hand, this functionality is easy in R shiny, so I’m assuming that Dash would want to provide it.
Specifically, I’d like to have sliders that are indexed by a dropdown. So on a dropdown I’ll have A, B, and that would lead to either a slider that adjusts the value of A or a slider that adjusts the value of B. At all times, I’d like to have a bar plot that shows the values of A and B.
Below is code that does this except for one problem: if I adjust the value of A from its default, switch the dropdown to B, and then switch it back to A, A resets back to its default value.
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
app = dash.Dash(__name__)
app.layout = html.Div([
dcc.Dropdown(id='segselect', options = [{'label': 'A', 'value': 'A'},
{'label': 'B', 'value': 'B'}]),
html.Div(id='SliderAContainer'),
html.Div(id='SliderBContainer'),
dcc.Graph(id='plot_graph')
])
app.config['suppress_callback_exceptions']=True
@app.callback(Output('SliderAContainer', 'children'),
[Input('segselect', 'value')])
def return_containerA(seg):
if seg == 'A':
return html.Div(dcc.Slider(id='A', min = 0, max = 10, step = 1))
else:
return html.Div(dcc.Slider(id='A', min = 0, max = 10, step = 1), style={'display': 'none'})
@app.callback(Output('SliderBContainer', 'children'),
[Input('segselect', 'value')])
def return_containerB(seg):
if seg == 'B':
return html.Div(dcc.Slider(id='B', min = 0, max = 10, step = 1, value = 2))
else:
return html.Div(dcc.Slider(id='B', min = 0, max = 10, step = 1, value = 2), style={'display': 'none'})
@app.callback(
Output('plot_graph', 'figure'),
[Input('A', 'value'), Input('B', 'value')])
def plot_A(A, B):
return {
'data': [
{'y': [A, B], 'type': 'bar'},
],
}
if __name__ == '__main__':
app.run_server(debug=True, port=8041, dev_tools_hot_reload=False)
How can I make it so that A does not reset after switching the menu to B and back, without triggering a circular dependency? (Apologies for formatting—I’m new to dash and this plotly forum)