Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotly figure hide and display

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

like image 765
cevdokzna Avatar asked Jun 14 '18 08:06

cevdokzna


1 Answers

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:

  • python 3.6.4
  • dash 0.21.0
  • dcc 0.22.1
  • html 0.10.0
like image 125
lwileczek Avatar answered Sep 25 '22 20:09

lwileczek