Dash のコールバック

Dash と Plotly で作るダッシュボード

Alex Scriven

Data Scientist

コールバックとは

 

  • 操作で機能が実行
    • ユーザーが要素を操作
      • -> Python 関数が起動
        • --> 何かが更新される

$$

$$

$$

  • なぜ? 互換性ではなく、対話性を高める ✨
Dash と Plotly で作るダッシュボード

Dash のコールバック

  • まずはデコレータ関数
    • from dash import Input, Output を使用
  • Output: 関数の返り値の出力先
    • component_id: 対象コンポーネント
    • component_property: 変更するプロパティ
  • Input: コールバックのトリガー
    • component_property: 関数で使う値

 

@callback(

Output(component_id='my_plot', component_property='figure'),
Input(component_id='my_input', component_property='value')
)
def some_function(data): # Subset Data # Recreate Figure return fig
Dash と Plotly で作るダッシュボード

Dash のドロップダウン

 

dcc.Dropdown(id='title_dd',
             options=['Title 1', 'Title 2'])
  • 値のリスト
Dash と Plotly で作るダッシュボード

ドロップダウンのコールバック

app.layout =[

dcc.Dropdown(id='title_dd', options=['Title 1', 'Title 2']),
dcc.Graph(id='my_graph')])
@callback( Output(component_id='my_graph', component_property='figure'),
Input(component_id='title_dd', component_property='value') )
# @callback()
def update_plot(selection):
    title = "None Selected"
    if selection:
        title = selection

bar_fig = px.bar( data_frame=ecom_sales, title=f'{title}', x='Total Sales ($)', y='Country')
return bar_fig
Dash と Plotly で作るダッシュボード

最初のドロップダウン

Chrome ブラウザで、合計売上(x 軸)と国(y 軸)の棒グラフがあり、上部のドロップダウンに Title 1 と Title 2 の選択肢がある。マウスでそれぞれを選ぶと、グラフのタイトルが対応する値に変わる

Dash と Plotly で作るダッシュボード

フィルターとしてのドロップダウン

  • よくある使い方:ドロップダウンでプロット用 DataFrame を絞り込む
# @callback()
def update_plot(input_country):
    country = 'All Countries'

sales = ecom_sales.copy(deep=True)
if input_country: country = input_country sales = sales[sales['Country'] == country]
bar_fig = px.bar( data_frame=sales, title=f"Sales in {country}", x='Total Sales ($)', y='Country') return bar_fig
Dash と Plotly で作るダッシュボード

動くフィルター

 

Chrome ブラウザで、合計売上(x 軸)と国(y 軸)の棒グラフがあり、上部のドロップダウンに国名の選択肢がある。各国を選ぶと、タイトルがその値に変わり、グラフは単一の棒に絞られる

Dash と Plotly で作るダッシュボード

練習してみましょう!

Dash と Plotly で作るダッシュボード

Preparing Video For Download...