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 62 63
| import dash import dash_core_components as dcc import dash_html_components as html import plotly.express as px from dash.dependencies import Input, Output, State, MATCH, ALLSMALLER
gapminder = px.data.gapminder()
half_style = {'width':'50%', 'display':'inline-block'}
app = dash.Dash(__name__)
app.layout = html.Div( [ html.Button('Push', id='button1', n_clicks=0), html.Div(id='div1', children=[]) ], style={'width':'90%', 'margin':'2% auto'} )
@app.callback( Output('div1', 'children'), Input('button1', 'n_clicks'), State('div1', 'children'), prevent_initial_calll=True ) def update_layout(n_clicks, children): new_layout = html.Div( [ dcc.Dropdown( id={'type':'dropdown1', 'index':n_clicks}, options=[{'label':c, 'value':c} for c in gapminder.country.unique()], value=gapminder.country.unique()[n_clicks - 1] ), dcc.Dropdown( id={'type':'dropdown2', 'index':n_clicks}, options=[ {'label':col, 'value':col} for col in gapminder.columns[3:6] ], value="lifeExp" ), dcc.Graph(id={'type':'graph1', 'index':n_clicks}) ], style=half_style ) children.append(new_layout) return children
@app.callback( Output({'type':'graph1', 'index':MATCH}, 'figure'), Input({'type': 'dropdown1', 'index':ALLSMALLER}, 'value'), Input({'type': 'dropdown1', 'index':MATCH}, 'value'), Input({'type': 'dropdown2', 'index':MATCH}, 'value') ) def update_graph(allsmaller_value, matching_values, selected_col): selected_value = allsmaller_value + [matching_values] selecred_coountries = gapminder[gapminder['country'].isin(selected_value)] return px.line(selecred_coountries, x='year', y=selected_col, color='country')
if __name__ == '__main__': app.run_server(debug=True)
|