Callbacks in Dash

Dashboards mit Dash und Plotly erstellen

Alex Scriven

Data Scientist

Was sind Callbacks?

 

  • Funktionalität durch Interaktion ausgelöst
    • Ein Element wird benutzt
      • -> Eine Python-Funktion wird ausgelöst
        • --> Etwas ändert sich

$$

$$

$$

  • Warum? Mehr Interaktivität ✨
Dashboards mit Dash und Plotly erstellen

Callbacks in Dash

  • Beginne mit der Decorator-Funktion
    • Verwendet from dash import Input, Output
  • Output: Wohin der Funktionswert geht
    • component_id: Komponente identifizieren
    • component_property: Was geändert wird
  • Input: Was den Callback auslöst
    • component_property: Was in der ausgelösten Funktion genutzt wird

 

@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
Dashboards mit Dash und Plotly erstellen

Dropdowns in Dash

 

dcc.Dropdown(id='title_dd',
             options=['Title 1', 'Title 2'])
  • Liste von Werten
Dashboards mit Dash und Plotly erstellen

Ein 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
Dashboards mit Dash und Plotly erstellen

Unser erstes Dropdown

Eine GIF-Aufnahme eines Chrome-Browsers mit einem Balkendiagramm der Gesamterlöse (x-Achse) und Länder (y-Achse). Darüber ein Dropdown mit „Title 1" und „Title 2". Die GIF zeigt, wie jeweils ausgewählt wird und der Diagrammtitel zum Dropdown-Wert wechselt

Dashboards mit Dash und Plotly erstellen

Dropdown als Filter

  • Häufiger Fall – Dropdown filtert den 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
Dashboards mit Dash und Plotly erstellen

Der Filter in Aktion

 

Eine GIF-Aufnahme eines Chrome-Browsers mit einem Balkendiagramm der Gesamterlöse (x-Achse) und Länder (y-Achse). Darüber ein Dropdown mit Ländernamen. Die GIF zeigt die Auswahl, der Titel passt sich an und die Grafik wird auf einen einzelnen Balken gefiltert

Dashboards mit Dash und Plotly erstellen

Lass uns üben!

Dashboards mit Dash und Plotly erstellen

Preparing Video For Download...