I have a problem with hiding and showing a graph in the Python framework, Dash. I define a new graph:
html.Div([
dcc.Graph(id = 'graph'),
],),
After I update my trace data with a callback function I return it and it is shown in the graph, but if nothing is selected from my dropdown menu I do
if not input or input == []:
return {'display': 'none'}
so that my graph is not shown, but it doesn't work for some reason. Is there a workaround?
Thank you in advance
You can set the id
element for the Div holding your graph and hide the whole div by using @app.callback
on the style
element.
html.Div(id="graph-container", children= [
dcc.Graph(id = 'graph'),
]),
@app.callback(Output('graph-container', 'style'), [Input('input_widget','value')])
def hide_graph(input):
if input:
return {'display':'block'}
else:
return {'display':'none'}
To see this code in action you can test out my code:
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
app = dash.Dash()
app.layout = html.Div(children=[
html.H1(children='Hello Dash'),
html.Div(children='''
Dash: A web application framework for Python.
'''),
html.Label("Show?"),
dcc.Dropdown(
id="my-input",
options = [
{'label':'Yes', 'value':True},
{'label':'No', 'value':False}
],
value = True
),
html.Div(
id="graph-container",
children = [
dcc.Graph(
id='example-graph',
figure={
'data': [
{'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},
{'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'},
],
'layout': {
'title': 'Dash Data Visualization'
}
}
)
])
])
@app.callback(Output('graph-container', 'style'), [Input('my-input', 'value')])
def hide_graph(my_input):
if my_input:
return {'display':'block'}
return {'display':'none'}
if __name__ == '__main__':
app.run_server(port=8125, debug = True)
Note I used the following versions:
Thanks lwileczek for the answer . I wanted to provide an update as the code needs a few minor tweaks to work in the following environment:
When I copied lwileczek's code into the above environment, dash through an error about passing a bad argument into the dropdown. After a couple of moments of trial and error, I was able to make the code work if I changed the values in the dropdown to strings and modified the conditional in the callback so that it was doing a string comparison as opposed to expecting the value to be a boolean.
The code for the dropdown looks like:
dcc.Dropdown(
id = 'my-input',
options = [
{'label':'Yes', 'value':'Yes'},
{'label':'No', 'value':'No'}
],
value='Yes'
),
The code for the conditional in the callback becomes:
if my_input == 'Yes':
return {'display': 'block'}
return {'display': 'none'}
(This should probably be a comment, but I don't have enough points to post a comment)
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.