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 浏览器的动图:上方有下拉菜单(选项为 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...