TaxpayersMoney
TaxpayersMoney

Reputation: 689

How to populate charts with data on clicking button in Dash with python

I am experimenting with Dash/Plotly. I can't work out how to populate charts with data on the click of a button. I know that if I pass the same thing I am returning from my callbacks directly to the figure argument in the app layout the chart works. I know that I can get the callback to change the text of a heading. I hit the submit button and the chart doesn't change. Here is my code:

app = dash.Dash(__name__, assets_external_path=assets)

app.layout = html.Div(children=[

    html.Div(className='parent', children=[

        html.Div(className='pD', children=[

           dcc.Dropdown(id='size', options=[
                {'label': 'Small', 'value': 'small'},
                {'label': 'Medium', 'value': 'medium'},
                {'label': 'Large', 'value': 'large'}
            ])

        ]),

        html.Div(className='submit', children=[

            html.Button('Submit', id='submit', n_clicks=0)

        ]),

        html.Div(className='graph_box cD', children=[dcc.Graph(id='graph')])

    ]),

])

@app.callback(
    Output('graph', 'figure'),
    [Input('submit', 'n_clicks')],
    [State('size', 'value')]
)
def update_chart(clicks, size):
    if clicks > 1:        
        return {'data': [{'x': np.random.randint(0, 100, 1000), 'type': 'histogram'}]}

app.run_server(debug=False, port=8000)

Upvotes: 0

Views: 3289

Answers (1)

coralvanda
coralvanda

Reputation: 6596

I have it working with the following changes:

initialize your graph with an empty figure:

dcc.Graph(
    id='graph',
    figure={}
)])

And change your callback so that it never returns None, but at least returns an empty figure for the graph element. Changing the condition to use clicks as a simple truthy condition helps, too.

def update_chart(clicks, size):
    if clicks:
        return {'data': [{'x': np.random.randint(0, 100, 1000), 'type': 'histogram'}]}
    else:
        return {'data': [], 'type': 'histogram'}

Upvotes: 3

Related Questions