Callbacks in Dash

Créer des tableaux de bord avec Dash et Plotly

Alex Scriven

Data Scientist

What are callbacks?

 

  • Functionality triggered by interaction
    • A user interacts with an element
      • -> A Python function is triggered
        • --> Something is changed

$$

$$

$$

  • Why? Enhances interactivity ✨
Créer des tableaux de bord avec Dash et Plotly

Callbacks in Dash

  • Start with the decorator function
    • Uses from dash import Input, Output
  • Output: Where to send the function return
    • component_id: Identify the component
    • component_property: What will be changed
  • Input: What triggers the callback
    • component_property: What to use in triggered function

 

@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
Créer des tableaux de bord avec Dash et Plotly

Dropdowns in Dash

 

dcc.Dropdown(id='title_dd',
             options=['Title 1', 'Title 2'])
  • List of values
Créer des tableaux de bord avec Dash et Plotly

A 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
Créer des tableaux de bord avec Dash et Plotly

Our first dropdown

A gif of a chrome web browser which has a bar chart of total sales (x-axis) and country (y-axis) with a dropdown above which has options of Title 1 and Title 2. The gif has the mouse select each of these, and the title in the graph changes to the associated dropdown value

Créer des tableaux de bord avec Dash et Plotly

Dropdown as a filter

  • Common use case - dropdown filters the plot 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
Créer des tableaux de bord avec Dash et Plotly

The filter in action

 

A gif of a chrome web browser which has a bar chart of total sales (x-axis) and country (y-axis) with a dropdown above which has options of country names. The gif has the mouse select each of these, and the title in the graph changes to the associated dropdown value and filters the chart to a single bar

Créer des tableaux de bord avec Dash et Plotly

Let's practice!

Créer des tableaux de bord avec Dash et Plotly

Preparing Video For Download...