-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontrolling_callbacks_with_states_button.py
61 lines (51 loc) · 2.13 KB
/
controlling_callbacks_with_states_button.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from dash import Dash, html, dcc, Input, Output, State
import pandas as pd
import plotly.express as px
happiness = pd.read_csv('world_happiness.csv')
app = Dash()
app.layout = html.Div([
html.H1('World Happiness Dashboard'),
html.P(['This dashboard shows the happiness score.',
html.Br(),
html.A('World Happiness Report Data Source',
href='https://worldhappiness.report/',
target='_blank')]),
dcc.RadioItems(id='region-radio',
options=happiness['region'].unique(),
value='North America'),
dcc.Dropdown(id='country-dropdown'),
dcc.RadioItems(id='data-radio',
options={
'happiness_score': 'Happiness Score',
'happiness_rank': 'Happiness Rank'
},
value='happiness_score'),
html.Br(),
html.Button(id='submit-button',
n_clicks=0,
children='Update the Output'),
dcc.Graph(id='happiness-graph'),
html.Div(id='average-div')])
@app.callback(
Output('country-dropdown', 'options'),
Output('country-dropdown', 'value'),
Input('region-radio', 'value'))
def update_dropdown(selected_region):
filtered_happiness = happiness[happiness['region'] == selected_region]
country_options = filtered_happiness['country'].unique()
return country_options, country_options[0]
@app.callback(
Output('happiness-graph', 'figure'),
Output('average-div', 'children'),
Input('submit-button', 'n_clicks'),
State('country-dropdown', 'value'),
State('data-radio', 'value'))
def update_graph(button_click, selected_country, selected_data):
filtered_happiness = happiness[happiness['country'] == selected_country]
line_fig = px.line(filtered_happiness,
x='year', y=selected_data,
title=f'{selected_data} in {selected_country}')
selected_avg = filtered_happiness[selected_data].mean()
return line_fig, f'The average {selected_data} for {selected_country} is {selected_avg}'
if __name__ == '__main__':
app.run_server(debug=True)