Dash 中的回呼函式

使用 Dash 與 Plotly 建立儀表板

Alex Scriven

Data Scientist

什麼是回呼?

 

  • 互動觸發功能
    • 使用者與元件互動
      • -> 觸發 Python 函式
        • --> 發生變更

$$

$$

$$

  • 為何使用?提升互動性 ✨
使用 Dash 與 Plotly 建立儀表板

Dash 中的回呼函式

  • decorator 函式開始
    • 使用 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 瀏覽器的動圖:上方有下拉選單(含 Title 1、Title 2),下方是長條圖,x 軸為總銷售額、y 軸為國家。滑鼠依序選取後,圖表標題會改為對應的下拉值

使用 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...