Callbacks in Dash

Building Dashboards with Dash and 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
Building Dashboards with Dash and Plotly

Callbacks in Dash

  • Start with the decorator function
    • Uses from dash.dependencies 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

 

@app.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
Building Dashboards with Dash and Plotly

Dropdowns in Dash

 

dcc.Dropdown(id='title_dd',
             options=[{'label':'Title 1', 
                       'value':'Title 1'},
                      {'label':'Title 2', 
                       'value':'Title 2'}]),
  • List of label-value dictionaries
Building Dashboards with Dash and Plotly

A dropdown callback

app.layout = html.Div(children=[

dcc.Dropdown(id='title_dd', options=[{'label':'Title 1', 'value':'Title 1'}, {'label':'Title 2', 'value':'Title 2'}]),
dcc.Graph(id='my_graph')])
@app.callback( Output(component_id='my_graph', component_property='figure'),
Input(component_id='title_dd', component_property='value') )
#@app.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
Building Dashboards with Dash and 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

Building Dashboards with Dash and Plotly

Dropdown as a filter

  • Common use case - dropdown filters the plot DataFrame
#@app.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'] == input_country]
bar_fig = px.bar( data_frame=sales, title=f"Sales in {country}", x='Total Sales ($)', y='Country') return bar_fig
Building Dashboards with Dash and Plotly

Let's practice!

Building Dashboards with Dash and Plotly

Preparing Video For Download...