Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 42 ยท Dash and Deployment

Dash Callbacks and Live Graphs

Make Dash apps interactive with callbacks: Input, Output and State, multiple outputs, chained callbacks, click events, dcc.Store, and live updating graphs with dcc.Interval.

A layout alone is a static page. Callbacks make a Dash app react: you write an ordinary Python function, and tell Dash which component properties are its inputs and which property receives the result. Whenever an input changes in the browser, Dash calls your function on the server and sends the returned value back to the page. You never write JavaScript or manage requests yourself.

This lesson covers the callback model, the most useful patterns (several outputs, chained dropdowns, click-to-detail, shared data) and live graphs that update every few seconds. As in the previous lesson, the runnable examples use the real Dash library in your browser and call the app through Flask's test client instead of a web server.

The callback model

Python
from dash import Dash, html, dcc, Input, Output, State, callback

@callback(
    Output("graph", "figure"),        # which property gets the return value
    Input("continent", "value"),      # which property triggers the function
)
def update_graph(continent):
    ...
    return fig
  • Output(component_id, component_property): the property that will be replaced.
  • Input(component_id, component_property): when this property changes, the function runs.
  • State(component_id, component_property): a value that is read but does not trigger the function (for example, text in a box, read when a button is clicked).
  • The function receives one argument per Input and State, in the order written, and returns one value per Output.

The @callback decorator (or @app.callback) registers the function. Dash also calls it once at page load for every callback so that outputs start in a consistent state, unless you set prevent_initial_call=True.

sequenceDiagram
    participant U as User
    participant B as Browser
    participant S as Dash server
    U->>B: picks "Asia" in the dropdown
    B->>S: POST /_dash-update-component (inputs, state)
    S->>S: runs update_graph("Asia")
    S-->>B: JSON: new figure
    B-->>U: graph redraws

Each change is one request. The function runs on the server; the browser only draws.

A working app, tested through the test client

In the example, we write the figure builder as a plain function, register it as a callback, then act as the browser: we send the same request that the page would send and print the answer.

Python A real callback: dropdown to figure (Dash)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Three things are visible here. First, the response for each output is keyed by component id and property. Second, with several outputs the callback is registered under a combined name (..graph.figure...summary.children..). Third, the whole figure travels as JSON on every update: for large figures use Patch (below).

Multiple inputs, State and buttons

A callback can have many inputs. It runs when any of them changes. To run only when a button is pressed, make the button the Input and the other controls State:

Python
@callback(
    Output("result", "children"),
    Input("go", "n_clicks"),                 # triggers the function
    State("name", "value"), State("age", "value"),   # read, but do not trigger
    prevent_initial_call=True,
)
def greet(n_clicks, name, age):
    return f"Hello {name}, you are {age}."

n_clicks counts clicks. prevent_initial_call=True avoids running at page load with an empty form. To know which input fired in a callback with several, use dash.ctx.triggered_id.

Chained callbacks and click events

Outputs of one callback can be inputs of another, so you can build dependent dropdowns: the country list depends on the continent. And since dcc.Graph exposes clickData, hoverData and selectedData, a click on a chart can drive a detail panel, which is where customdata from hover, click and events pays off:

Python
@callback(Output("country", "options"), Output("country", "value"), Input("continent", "value"))
def country_choices(continent):
    names = sorted(df[df.continent == continent].country)
    return names, names[0]

@callback(Output("detail", "children"), Input("graph", "clickData"))
def show_clicked(click):
    if not click:
        return "Click a bubble"
    point = click["points"][0]
    return f"{point['hovertext']}: life expectancy {point['y']:.1f}"

Dash builds a dependency graph from all callbacks and runs them in the right order. A component property can be the Output of only one callback (unless you use allow_duplicate=True), and circular dependencies are an error.

Sharing data between callbacks: dcc.Store

Callbacks must not share Python globals that they modify (workers do not share memory; see deploying Plotly apps). When one callback computes something that others need (a filtered table, a model result), save it in a dcc.Store in the browser and use it as an input:

Python
dcc.Store(id="filtered")                      # in the layout

@callback(Output("filtered", "data"), Input("year", "value"))
def filter_data(year):
    return df[df.year == year].to_dict("records")   # JSON-serializable

@callback(Output("graph", "figure"), Input("filtered", "data"))
def draw(records):
    return px.scatter(pd.DataFrame(records), x="gdpPercap", y="lifeExp")

The expensive filter runs once, and the data is sent to the browser. Keep stores small (a few MB); for big tables use a server cache keyed by the inputs.

Live graphs with dcc.Interval

A live graph updates by itself: server load, sensor readings, orders arriving. dcc.Interval(id="tick", interval=1000) is an invisible component that increases its n_intervals property every 1000 ms, and any callback can use that as an input. Each tick, the callback produces a new figure from the freshest data.

Python A live graph driven by ticks (Dash)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

uirevision="keep" is the small detail that makes live charts pleasant: without it, every update resets any zoom or pan the user made. Setting any constant value tells Plotly "this is the same chart, keep the UI state".

The same idea without a server is just a browser timer. Plotly.js has extendTraces, which appends points efficiently instead of redrawing everything; this is what high-frequency dashboards use.

The browser-side version: extendTraces on a timer

The last argument of extendTraces (30) is the maximum number of points to keep, so the line scrolls instead of growing forever.

Making callbacks faster and safer

  • Patch() returns only the change: patch = Patch(); patch["data"][0]["y"].append(v); return patch sends a few bytes instead of the whole figure.
  • Clientside callbacks (app.clientside_callback("function(x){...}", Output(...), Input(...))) run JavaScript in the browser with no server round trip.
  • Background callbacks (background=True) run long computations in a worker queue and report progress.
  • dcc.Loading wraps a component and shows a spinner while its callback runs.
  • Validate inputs. A callback is a public endpoint: never trust values from the browser, and do not build SQL or file paths from them.
  • Handle None. Inputs are None before the user selects anything; return dash.no_update or PreventUpdate when there is nothing to do.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between Input and State?

    Use State for values you want to read at the moment a button is pressed without triggering on every keystroke.
  2. 2. What does dcc.Interval(interval=1000) do?

    n_intervals is a counter property. Using it as an Input makes the callback run on every tick.
  3. 3. Why set uirevision on a live figure?

    A constant uirevision tells Plotly that the new figure continues the old one, so UI state is preserved.
  4. 4. Callbacks must not rely on a global variable they modify, because:

    Share state through dcc.Store, a database or a cache.

Summary

  • A callback maps Input (and State) properties to Output properties through a Python function.
  • Dash runs callbacks at load (unless prevent_initial_call), chains them by dependency and returns JSON to the browser.
  • clickData, hoverData and selectedData turn charts into controls; customdata identifies the clicked row.
  • Share data with dcc.Store, not global variables; speed up with Patch, clientside and background callbacks.
  • dcc.Interval plus a callback makes live graphs; uirevision preserves the user's view.

Next: Exporting and Embedding Figures