Dash⑯(コールバック/複数入力)

tipsデータセットを用いて、出力と入力が2つずつあるアプリケーションを作成します。

複数の入出力があるコールバック

曜日を選択するドロップダウンと、グラフを選択するドロップダウンを配置します。

グラフはドロップダウンで選択されたグラフ(棒グラフ/散布図)が表示されます。

  • 棒グラフ
    曜日ごとの売り上げの累計を表示。
  • 散布図
    X軸に会計額、Y軸にチップの金額を表示。

コールバック関数では選択された曜日グラフの種類を抽出します。

この選択された曜日とグラフの種類に合わせてグラフを描画し、見出しと図形(figure)を返します。

[ソースコード]

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
64
65
66
67
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

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

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

app.layout = html.Div(
[
html.H3(id='title', style={'textAlign':'center'}),
html.Div(
[
html.Div(
[
html.H4('曜日選択'),
dcc.Dropdown(
id='day_selector',
options=[
{'value':d, 'label':d}
for d in tips.day.unique()
],
multi=True,
value=['Thur', 'Fri', 'Sat', 'Sun']
)
]
),
html.Div(
[
html.H4('グラフ選択'),
dcc.Dropdown(
id='graph_selector',
options=[
{'value':'bar', 'label':'bar'},
{'value':'scatter', 'label':'scatter'}
],
value='bar',
)
]
)
]
),
dcc.Graph(id='app-graph')
]
)

# コールバックの定義
@app.callback(
Output('title', 'children'),
Output('app-graph', 'figure'),
Input('day_selector', 'value'),
Input('graph_selector', 'value'),
)
def update_graph(selected_days, selected_graph):
selected_df = tips[tips['day'].isin(selected_days)] # データフレーム作成
if selected_graph == 'bar':
title = ('曜日ごとの売り上げ(棒グラフ)',)
figure = px.bar(selected_df, x='day', y='total_bill', height=500)
else:
title = ('テーブルごとデータ(散布図)',)
figure = px.scatter(selected_df, x='total_bill', y='tip', color='smoker', height=500)
return title, figure

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

曜日選択用のドロップダウンは複数選択とし、グラフ選択用のドロップダウンは単数選択としました。

曜日の選択肢は、データのday列のユニーク要素を使って作成しています。

上記ソースを実行すると、コンソールにURLが表示されるのでブラウザで表示します。

[ブラウザで表示]

選択された曜日がグラフに反映され、選択された種類のグラフが表示されることを確認できます。