Chained callbacks

Building Dashboards with Dash and Plotly

Alex Scriven

Data Scientist

Why chain callbacks?

 

  • So far callbacks cause:
    • Regenerate plots
    • Change HTML / text

$$

  • What about callback triggering another callback?
    • Use case: conditional dropdown
Building Dashboards with Dash and Plotly

A common example

 

A gif of two dropdowns side-by-side. The first has the placeholder text Make, and the second has Model. As the mouse selects Audi from the first dropdown then moves to the second dropdown, it is clear the available options for then the second dropdown have been filtered to only models that are for Audi cars

Building Dashboards with Dash and Plotly

Inputs and outputs

  • The trick: be aware of callback pathways (inputs and outputs)
  • Helpful tool: an input-output diagram

$$

  • The flow:
    • User changes value of first dropdown (INPUT)
    • A callback subsets and returns options of the second dropdown (OUTPUT)
    • A second callback could be triggered (INPUT) by the value property of the second dropdown.

A flow chart with rectangles and arrows connecting boxes vertically. Between boxes are small text boxes. The first box has the word user, it has an arrow to the second box with the words "Major Category dropdown". Between was a small text box with the word "value". There is an arrow below this connecting to a box with the words "Minor category dropdown". The text box in between says Options. This box connects via an arrow to the next and final box down, with the words "(Optional) More callbacks" with a textbox in between with the word "Options"

Building Dashboards with Dash and Plotly

Chained callbacks in Dash

 

@callback(
  Output('minor_cat_dd', 'options'),
  Input('major_cat_dd', 'value'))

def update_major_cat(major_cat_dd): # Filter options (list of dicts) return minor_options

 

@callback(
  Output('minor_cat_dd', 'value'),
  Input('minor_cat_dd', 'options'))

def update_minor_cat(minor_cat_options): # Pick a default value return chosen_value
Building Dashboards with Dash and Plotly

Multiple outputs

  • Updating multiple elements

$$

@callback(
  Output('my_title', 'children'),
  Output('minor_cat_dd', 'value'),
  Input('minor_cat_dd', 'options')
)
def some_function(input):
  # function body
  return title_value, dropdown_value
Building Dashboards with Dash and Plotly

Multiple outputs diagram

A flow chart diagram that extends the one previously put up. Instead of the final box, which had the text "(Optional) More callbacks," there are two arrows to two boxes below, side-by-side. They have the text "Minor Category Dropdown" and "HTML Title," both of which have an arrow to the optional box that was a the bottom of the last diagram.

Building Dashboards with Dash and Plotly

Let's practice!

Building Dashboards with Dash and Plotly

Preparing Video For Download...