Dash⑱(パターンマッチング・コールバック/ALLセレクタ その2)

ALLセレクタでグラフ表示

前回記事では、ALLセレクタを使って複数のコンポーネントの選択値をまとめて取得することができました。

今回は、選択した複数の選択値を折れ線グラフに反映します。

[ソースコード]

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
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, ALL

gapminder = px.data.gapminder() # データの読み込み

app = dash.Dash(__name__) # Dashインスタンスを生成

app.layout = html.Div(
[
html.Button('Push', id='button1', n_clicks=0),
html.Div(id='div1', children=[]),
html.Div(id='select1', 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_layouth(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]
)
]
)
children.append(new_layout)
return children

# コールバックの定義②
@app.callback(
Output('select1', 'children'),
Input({'type': 'dropdown1', 'index':ALL}, 'value'),
prevent_initial_calll=True
)
def update_graph(selected_values):
# 全てのドロップダウンで選択された国のデータを作成し、可視化する。
selected_countries = gapminder[gapminder["country"].isin(selected_values)]
return dcc.Graph(
figure=px.line(selected_countries, x='year', y='lifeExp', color='country')
)

if __name__ == '__main__':
app.run_server(debug=True) # アプリケーションを起動

2つめのコールバック関数(update_graph)で、各ドロップダウンで選択された全ての値を折れ線グラフに反映しています。

[ブラウザで表示]

国名を複数選択すると、そのデータが折れ線グラフに反映されることが確認できます。