Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 31 ยท Plotly

Dashboards with Dash and Callbacks

Build a Plotly Dash app: a layout of components, callbacks as reactive functions, State, multiple outputs, and how to deploy it, with a runnable callback-graph model.

A chart on its own is a picture. A dashboard is a small application: the user picks a country in a dropdown, drags a year slider, and the charts and numbers change. Plotly's answer for Python programmers is Dash. You describe the page as a tree of components, write ordinary Python functions that compute what each component should show, and Dash wires them together. You write no JavaScript for the common case.

The core idea is the callback: a Python function declared with the inputs it listens to and the outputs it updates. When an input changes in the browser, Dash calls your function on the server and sends the result back to the browser. That is the same idea as a spreadsheet formula: cells (component properties) depend on other cells, and changing one cell recalculates the ones that depend on it.

Dash needs a running Python web server, so it cannot run on this site. All Dash and Plotly code below is read-only. The runnable examples are stand-ins: a small JavaScript model of Dash's dependency graph that shows when callbacks run, in what order, and why. It is an explanation of the idea, not the real framework, and the real Dash does more (a browser front end, network calls, caching).

A first app

Install with pip install dash (it brings Plotly). A complete app fits on one screen:

Python
from dash import Dash, dcc, html, Input, Output, callback
import plotly.express as px

df = px.data.gapminder()

app = Dash(__name__)

app.layout = html.Div(
    [
        html.H1("Life expectancy over time"),
        dcc.Dropdown(
            id="country",
            options=sorted(df["country"].unique()),
            value="Canada",
            clearable=False,
        ),
        dcc.Graph(id="life-graph"),
    ],
    style={"maxWidth": "900px", "margin": "0 auto"},
)


@callback(Output("life-graph", "figure"), Input("country", "value"))
def update_graph(country):
    subset = df[df["country"] == country]
    return px.line(subset, x="year", y="lifeExp", markers=True, title=country)


if __name__ == "__main__":
    app.run(debug=True)

Run python app.py and open http://127.0.0.1:8050. (Older tutorials call app.run_server; current Dash versions use app.run.) With debug=True, Dash reloads when you save the file and shows errors in the browser.

Layout: a tree of components

app.layout is a tree. html.Div, html.H1 and friends mirror HTML tags from the dash.html module. Interactive components come from dash.dcc (Dash Core Components): Dropdown, Slider, RangeSlider, Input, Checklist, RadioItems, DatePickerRange, Graph, Store, Interval and more. Tables come from dash.dash_table.DataTable. Third-party packages add the rest; for example dash-bootstrap-components supplies a responsive grid and styled controls.

Every component that takes part in a callback needs a unique id. Each component has properties, and a property such as value of a dropdown or figure of a graph is the unit that callbacks read and write. A property is addressed by the pair (id, property).

Callbacks: functions from properties to properties

The decorator @callback(Output(...), Input(...)) registers the function. Dash passes the current values of the inputs as arguments, in order, and puts the return value into the output. Some points you will use constantly:

  • Several inputs give several arguments: @callback(Output("g", "figure"), Input("country", "value"), Input("year", "value")).
  • Several outputs are returned as a tuple in the same order as the Output list.
  • State reads a value without triggering the callback. Use it for "submit" patterns: the callback listens to a button's n_clicks and merely reads the text field as State.
  • prevent_initial_call=True stops the callback from running once at page load.
  • raise PreventUpdate (from dash.exceptions) and returning dash.no_update let a callback decide that nothing should change, which also stops downstream callbacks.
  • Pattern-matching ids such as {"type": "filter", "index": ALL} allow callbacks over components that are created dynamically.

By default every callback also runs once when the page loads, so that every output has a value. That is why a dashboard shows charts immediately without a click.

The callback graph

Callbacks are not isolated. One callback's output can be another callback's input, so together they form a directed graph. Dash orders the work so that a callback runs only after the callbacks that feed its inputs have finished. This graph decides what happens at page load and after every click.

flowchart LR
    R["region.value"] --> C1["update_countries"]
    C1 --> O["country.options"]
    C1 --> V["country.value"]
    V --> C2["update_graph"]
    Y["year.value"] --> C2
    C2 --> F["graph.figure"]
    F --> C3["update_caption"]
    C3 --> T["caption.children"]

Names like region.value are component properties; the update functions are callbacks. Changing the region triggers three callbacks in a chain.

The first runnable example models this. It stores properties in a dictionary, registers callbacks with inputs and outputs, and runs them in dependency order. Run it and read the log: at start-up every callback runs once, and a change of the region cascades downstream.

JS A callback graph with dependency order (stand-in)

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

No output.

Three things to notice in the log. First, at page load the callbacks run in dependency order, not in the order they were written. Second, changing the year runs only update_graph and update_caption; update_countries does not listen to the year. Third, changing the region runs all three, and update_graph runs once even though both the country list and its value changed upstream. In real Dash the same ordering rules apply, with each run being a request to your server.

Rules the graph enforces

Dash checks the graph when the app starts and when it handles requests, and a few mistakes are common:

  • Circular dependencies (A updates B and B updates A) are rejected, or need special care. The next example detects them.
  • Two callbacks writing the same output raise an error by default. Combine them into one callback with several inputs, or opt in with allow_duplicate=True.
  • Ids that are not in the layout make the callback fail in the browser, unless the component is created dynamically and you set suppress_callback_exceptions=True deliberately.
JS Detecting cycles and duplicate outputs (stand-in)

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

No output.

Deployment notes

app.run(debug=True) starts Flask's development server, which is not meant for real traffic. Dash apps are Flask apps underneath, and the Flask object is available as app.server. In app.py add server = app.server, then serve it with a production server such as Gunicorn:

Terminal
pip install gunicorn
gunicorn app:server --workers 2 --bind 0.0.0.0:8050

A few practical rules follow from the architecture:

  • The server holds your data. Load large files once at start-up, not inside a callback. Callbacks may run in several worker processes, so never keep per-user state in Python globals. Keep it in the browser with dcc.Store, or in a shared cache or database.
  • Every interaction is a network round trip. For purely visual effects (such as changing a chart title) consider a client-side callback written in JavaScript so no request is needed.
  • Slow callbacks block the interface. Use caching (functools.lru_cache or Flask-Caching), pre-aggregate data, or use background callbacks for long jobs.
  • Hosting. Any host that can run a Python web process works: a container platform, a virtual machine behind a reverse proxy, or a Python-friendly platform service. Put it behind HTTPS.

If you prefer to keep the logic in the browser, plotly.js with your own handlers (previous lesson, Plotly.js in the Browser) needs no server at all but takes more JavaScript. For linked views with a Python server and a different style, see Bokeh Server and Streaming Data.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a Dash callback declare?

    A callback is a Python function plus a declaration of the component properties it listens to and the properties it updates.
  2. 2. When should you use State instead of Input?

    A State value is passed to the function but changing it does not run the callback. It is ideal for form fields that are read when a button is clicked.
  3. 3. Why shouldn't a production Dash app store per-user data in a Python global variable?

    Each worker process has its own globals, and one process serves many users. Per-user state belongs in dcc.Store, a cache or a database.
  4. 4. Callback A outputs graph.figure, callback B takes graph.figure as an Input. Which statement is true?

    Chained callbacks are normal. Dash orders them so B runs after A finishes and receives the new figure, unless A returns no_update.
  5. 5. Which command serves a Dash app with a production server?

    The Flask server object is app.server, and Gunicorn (or a similar WSGI server) runs it. The built-in debug server is for development only.

Summary

  • Dash turns Python functions into a web dashboard: a layout of components plus callbacks.
  • A callback names its Input properties, optional State properties and Output properties; chained callbacks form a dependency graph that Dash runs in order.
  • Callbacks run once at page load unless prevent_initial_call=True; no_update and PreventUpdate stop updates.
  • Circular dependencies and duplicate outputs are errors you should design away.
  • Deploy with server = app.server and Gunicorn; keep per-user state out of globals; remember each interaction is a round trip.
  • The Dash code here is read-only; the runnable examples model the callback graph.

Next: Bokeh Fundamentals, a second Python library for interactive charts.