1

I am following the dash tutorials and totally confused about how dash call upon functions. Following the second tute on this page https://dash.plotly.com/basic-callbacks. The same example is shown below. I am totally clueless where the update_figure function is even called but the graph is still plotted within the dashboard (i.e there is no mention of update_figure() function anywhere within the app.layout or app.callback).

So any ideas on how the function is passed on?

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv')

# initialize 
app = dash.Dash()

app.layout = html.Div([
    dcc.Graph(id = 'graph-with-slider'),
    dcc.Slider(
        id = 'year-slider',
        min = df['year'].min(),
        max = df['year'].max(), 
        value = df['year'].min(),
        marks = {str(year) : str(year) for year in df['year'].unique()},
        step = None
    )
])

@app.callback(
    Output('graph-with-slider','figure'),
    [Input('year-slider','value')]
)

def update_figure(selected_year):
    filtered_df = df[df.year == selected_year]

    fig = px.scatter(filtered_df, x = 'gdpPercap', y = 'lifeExp', size = 'pop', color = 'continent', hover_name = 'country', log_x = True, size_max = 55)

    fig.update_layout(transition_duration = 500)

    return fig

if __name__ == '__main__':
    app.run_server()
1
  • 1
    Just a sidenote, coralvanda is correct, but if you have significant state in your application dealing with the callbacks is a nightmare to figure out. Unfortunately I can't remember the solution, I just wanted you to know that if you ran into that problem you're not alone.
    – tomaszps
    Commented Jul 2, 2020 at 0:41

1 Answer 1

2

Dash does that under the hood using the @app.callback decorator. The function will be called whenever the Inputs change, and Dash will take the returned value from the callback to update the outputs.

2
  • Thanks for this. But imagine there were two functions instead of one like in the example. How would it know which one to run?
    – imantha
    Commented Jul 2, 2020 at 6:37
  • Dash will only allow one callback decorator per function definition, and Dash enforces that an output can only appear in one callback (in other words, no having two different callbacks that output to the same id/prop combination). Even if you have 10 callbacks triggered by clicking one button, Dash will run all of them and output as each callback declares. Let me know if that still doesn't answer your question.
    – coralvanda
    Commented Jul 2, 2020 at 23:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.