Callbacks ใน Dash

การสร้างแดชบอร์ดด้วย Dash และ Plotly

Alex Scriven

Data Scientist

Callbacks คืออะไร?

 

  • ฟังก์ชันที่ถูกเรียกใช้เมื่อมีการโต้ตอบ
    • ผู้ใช้โต้ตอบกับองค์ประกอบ
      • -> ฟังก์ชัน Python ถูกเรียกใช้งาน
        • --> บางสิ่งเปลี่ยนแปลง

$$

$$

$$

  • ทำไม? เพิ่มความสามารถเชิงโต้ตอบ ✨
การสร้างแดชบอร์ดด้วย Dash และ Plotly

Callbacks ใน Dash

  • เริ่มต้นด้วยฟังก์ชัน decorator
    • ใช้ from dash import Input, Output
  • Output: ส่งค่าที่ฟังก์ชันคืนมาไปที่ใด
    • component_id: ระบุ component
    • component_property: สิ่งที่จะถูกเปลี่ยนแปลง
  • Input: สิ่งที่กระตุ้น callback
    • 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

Dropdown ใน Dash

 

dcc.Dropdown(id='title_dd',
             options=['Title 1', 'Title 2'])
  • รายการค่า
การสร้างแดชบอร์ดด้วย Dash และ Plotly

Dropdown callback

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

Dropdown แรกของเรา

GIF แสดงเว็บเบราว์เซอร์ Chrome ที่มีแผนภูมิแท่งของยอดขายรวม (แกน x) และประเทศ (แกน y) พร้อม dropdown ด้านบนที่มีตัวเลือก Title 1 และ Title 2 เมื่อคลิกแต่ละตัวเลือก ชื่อกราฟจะเปลี่ยนตามค่าที่เลือก

การสร้างแดชบอร์ดด้วย Dash และ Plotly

Dropdown เป็นตัวกรอง

  • กรณีใช้งานทั่วไป — dropdown กรอง 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

ตัวกรองในการทำงาน

 

GIF แสดงเว็บเบราว์เซอร์ Chrome ที่มีแผนภูมิแท่งของยอดขายรวม (แกน x) และประเทศ (แกน y) พร้อม dropdown ด้านบนที่มีตัวเลือกชื่อประเทศ เมื่อคลิกแต่ละตัวเลือก ชื่อกราฟจะเปลี่ยนตามค่าที่เลือกและกรองแผนภูมิให้แสดงแท่งเดียว

การสร้างแดชบอร์ดด้วย Dash และ Plotly

มาฝึกกันเถอะ!

การสร้างแดชบอร์ดด้วย Dash และ Plotly

Preparing Video For Download...