Black Lives Matter. Please consider donating to Black Girls Code today.

[Solved] Create a Graph() dynamically e.g. once a Dropdown selection has been made

I would like my dashboard to create a Graph() upon a met condition (or collapse a plot if no data.)

This is relevant if e.g. a user has to upload their own data - so prior to this a user may not want a blank plot visible. I have followed Dash’s upload component example and the data populates a table, which only shows when data exists https://plot.ly/dash/dash-core-components/upload.

However, if I follow something similar for a plot it doesn’t work e.g. something along the lines of:

# example div:
html.Div(children=[html.H4('Please load a data file and select a column from dropdown menu in order to display visualisation below',`id='output-data-upload-graph')]),`

html.Div(dcc.Graph(id='dist_graph'), style={'display': 'none'})

@app.callback(Output('output-data-upload-graph', 'children'),
             [Input('target_col_dropdown', 'value'),
              Input('intermediate-value', 'children')])
def draw_target_col_dist(column, jsonified_data):

    dff = pd.read_json(jsonified_data)
    counts = dff[column].value_counts()
    keys = counts.index.tolist()
    values = counts.values.tolist()

    data = [go.Bar(
                    x=keys,
                    y=values
                  )
           ]
                                     
    return {'data': data}

Am I doing something wrong? I have noticed that my code works if I update a blank graph with data but only if the graph is already showing. If it isn’t , it doesn’t appear.

I have solved my problem and the results can be found by downloading and running a Dash from:

https://github.com/eddy-oj/Dash-dynamic-Graph-creation

I am not sure how I solved the problem as I was under the impression that I had tried this solution before. It’s probable that I had made a typo no a previous attempt that I was unaware of :wink:

2 Likes