Dash Tutorial: Build Your First Dashboard in Python

Build a Plotly Dash dashboard step by step: layout, callbacks, multiple inputs and outputs, side-by-side charts, click interactions, buttons with State, and deployment.

A Dash app has two parts: a layout that describes the components on the page, and callbacks, Python functions that update components when the user changes something. Install it with pip install dash, write both in app.py, and run python app.py to see the dashboard at http://127.0.0.1:8050. The code here targets Dash 4.5 and Plotly 6.

Quick Example

This app shows made-up weekly checkouts for a library system, with a dropdown to choose the branch. Save it as app.py:

import numpy as np
import pandas as pd
import plotly.express as px
from dash import Dash, Input, Output, State, callback, dcc, html

rng = np.random.default_rng(127)
weeks = pd.date_range("2025-11-24", periods=52, freq="W-MON")
branches = {"Central": 2400, "Eastside": 1300, "Harbor": 900, "Northgate": 1600}
formats = {"Books": 0.62, "Audiobooks": 0.24, "Films": 0.14}
season = 1 + 0.18 * np.sin(2 * np.pi * (np.arange(52) - 22) / 52)

loans = pd.DataFrame([
    {"week": week, "branch": branch, "format": fmt,
     "checkouts": int(rng.poisson(base * share * season[i]))}
    for branch, base in branches.items()
    for fmt, share in formats.items()
    for i, week in enumerate(weeks)
])

app = Dash()

app.layout = html.Div([
    html.H1("Library Checkouts"),
    html.Label("Branch"),
    dcc.Dropdown(list(branches), value="Central", id="branch", clearable=False),
    dcc.Graph(id="trend"),
], style={"maxWidth": "800px", "margin": "auto", "fontFamily": "sans-serif"})


@callback(Output("trend", "figure"), Input("branch", "value"))
def update_trend(branch):
    data = loans[loans["branch"] == branch]
    weekly = data.groupby(["week", "format"], as_index=False)["checkouts"].sum()
    return px.line(weekly, x="week", y="checkouts", color="format",
                   title=f"Weekly checkouts: {branch}", template="plotly_white",
                   labels={"week": "", "checkouts": "Checkouts", "format": "Format"})


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

Dash app titled Library Checkouts with a branch dropdown set to Central above a line chart of weekly checkouts for books, audiobooks and films

How Does a Dash App Work?

The layout is a tree of Python objects. html components such as html.Div and html.H1 become HTML tags, and dcc ("Dash Core Components") provides the interactive ones: dcc.Graph, dcc.Dropdown, dcc.Slider, dcc.RadioItems, dcc.DatePickerRange and others.

A callback connects components by id and property name:

  • Input("branch", "value") means "run this function when the dropdown's value changes".
  • Output("trend", "figure") means "put the return value in the graph's figure".
  • Function arguments arrive in the order the inputs are listed. The function's name doesn't matter.

Callbacks also run once when the page loads, which is why the chart is filled in before anyone touches the dropdown. Anything defined outside a callback, like loans, is created once at startup and shared by every user, so don't modify it inside a callback.

Multiple Inputs

List as many inputs as you need. Each later example reuses the imports and data from the Quick Example, so replace everything from app = Dash() down.

app = Dash()

app.layout = html.Div([
    html.H1("Compare Branches"),
    dcc.Dropdown(list(branches), value=["Central", "Northgate"], multi=True, id="picked"),
    dcc.RadioItems(["All formats", *formats], value="All formats", id="format", inline=True,
                   style={"margin": "12px 0"}),
    dcc.Graph(id="compare"),
], style={"maxWidth": "800px", "margin": "auto", "fontFamily": "sans-serif"})


@callback(
    Output("compare", "figure"),
    Input("picked", "value"),
    Input("format", "value"),
)
def compare(picked, fmt):
    data = loans[loans["branch"].isin(picked)]
    if fmt != "All formats":
        data = data[data["format"] == fmt]
    weekly = data.groupby(["week", "branch"], as_index=False)["checkouts"].sum()
    return px.line(weekly, x="week", y="checkouts", color="branch", title=fmt,
                   template="plotly_white",
                   labels={"week": "", "checkouts": "Checkouts", "branch": "Branch"})


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

Dash app with a multi-select dropdown of two branches, radio buttons for format and a line chart comparing the branches

If every branch is removed, picked is an empty list and the chart comes back empty.

Dashboard Layout with Multiple Outputs

Return one value per Output, in the same order. Here a single control updates three KPI cards and two charts. The side-by-side layout is CSS flexbox passed through style; React-style property names like flexWrap are camelCase.

app = Dash(title="Library dashboard")

CARD = {"flex": "1", "padding": "14px 18px", "background": "#f1f5f9", "borderRadius": "8px"}
ROW = {"display": "flex", "gap": "14px", "flexWrap": "wrap"}


def card(label, value):
    return html.Div([html.Div(label, style={"color": "#475569"}),
                     html.Div(value, style={"fontSize": "28px", "fontWeight": "bold"})],
                    style=CARD)


app.layout = html.Div([
    html.H2("Library Dashboard"),
    dcc.RadioItems(
        options=[{"label": "Last 4 weeks", "value": 4},
                 {"label": "Last 13 weeks", "value": 13},
                 {"label": "Full year", "value": 52}],
        value=13, id="period", inline=True, style={"marginBottom": "14px"}),
    html.Div(id="cards", style=ROW),
    html.Div([
        dcc.Graph(id="by-branch", style={"flex": "1", "minWidth": "320px"}),
        dcc.Graph(id="by-format", style={"flex": "1", "minWidth": "320px"}),
    ], style=ROW),
], style={"maxWidth": "900px", "margin": "auto", "fontFamily": "sans-serif"})


@callback(
    Output("cards", "children"),
    Output("by-branch", "figure"),
    Output("by-format", "figure"),
    Input("period", "value"),
)
def update_dashboard(n_weeks):
    data = loans[loans["week"].isin(weeks[-n_weeks:])]
    by_branch = data.groupby("branch", as_index=False)["checkouts"].sum()
    by_format = data.groupby("format", as_index=False)["checkouts"].sum()
    total = data["checkouts"].sum()

    cards = [
        card("Checkouts", f"{total:,}"),
        card("Per week", f"{total / n_weeks:,.0f}"),
        card("Busiest branch", by_branch.loc[by_branch["checkouts"].idxmax(), "branch"]),
    ]
    bars = px.bar(by_branch, x="branch", y="checkouts", title="By branch",
                  template="plotly_white", labels={"branch": "", "checkouts": ""},
                  color_discrete_sequence=["#0f766e"])
    donut = px.pie(by_format, names="format", values="checkouts", hole=0.55,
                   title="By format")
    for fig in (bars, donut):
        fig.update_layout(height=340, margin=dict(l=40, r=20, t=50, b=40))
    return cards, bars, donut


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

Dash dashboard with period radio buttons, three KPI cards, a bar chart of checkouts by branch and a donut chart by format

For larger layouts, put CSS in an assets/ folder next to app.py. Dash loads those files automatically, and you can use className instead of inline styles.

Click a Chart to Filter Another

Charts are inputs too. dcc.Graph has a clickData property that holds the clicked point, and it's None until the first click.

app = Dash()

totals = loans.groupby("branch", as_index=False)["checkouts"].sum().sort_values("checkouts")
bars = px.bar(totals, x="checkouts", y="branch", orientation="h", template="plotly_white",
              title="Click a branch", labels={"branch": "", "checkouts": "Checkouts"})
bars.update_layout(height=300)

app.layout = html.Div([
    dcc.Graph(id="branch-bars", figure=bars),
    dcc.Graph(id="detail"),
], style={"maxWidth": "800px", "margin": "auto", "fontFamily": "sans-serif"})


@callback(Output("detail", "figure"), Input("branch-bars", "clickData"))
def show_detail(click):
    branch = click["points"][0]["y"] if click else "Central"
    data = loans[loans["branch"] == branch]
    fig = px.area(data, x="week", y="checkouts", color="format", template="plotly_white",
                  title=f"{branch} by format",
                  labels={"week": "", "checkouts": "Checkouts", "format": "Format"})
    return fig


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

Dash app where clicking the Harbor bar shows a stacked area chart of Harbor checkouts by format

hoverData and selectedData (box or lasso selection) work the same way.

Wait for a Button with State

Input triggers a callback. State passes a value along without triggering it. Use it when the user should finish typing before anything happens.

app = Dash()

app.layout = html.Div([
    html.H3("Weekly target"),
    html.Div([
        dcc.Input(id="target", type="number", value=7000, step=500),
        html.Button("Update chart", id="apply", n_clicks=0),
    ], style={"display": "flex", "gap": "10px"}),
    html.P(id="message"),
    dcc.Graph(id="progress"),
], style={"maxWidth": "800px", "margin": "auto", "fontFamily": "sans-serif"})


@callback(
    Output("progress", "figure"),
    Output("message", "children"),
    Input("apply", "n_clicks"),
    State("target", "value"),
)
def apply_target(n_clicks, target):
    weekly = loans.groupby("week", as_index=False)["checkouts"].sum()
    target = target or 0                         # the box can be left empty
    weekly["met"] = np.where(weekly["checkouts"] >= target, "Met target", "Below target")
    fig = px.bar(weekly, x="week", y="checkouts", color="met", template="plotly_white",
                 color_discrete_map={"Met target": "#15803d", "Below target": "#cbd5e1"},
                 labels={"week": "", "checkouts": "Checkouts", "met": ""})
    fig.add_hline(y=target, line_dash="dash", line_color="#0f172a")
    hits = (weekly["checkouts"] >= target).sum()
    return fig, f"{hits} of {len(weekly)} weeks reached {target:,} checkouts."


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

Dash app with a target number box, an update button and a bar chart of weekly checkouts with weeks above the dashed target line in green

With several buttons feeding one callback, ctx.triggered_id (from dash import ctx) tells you which id fired it.

Debugging and Common Errors

app.run(debug=True) reloads the app when you save and shows errors in a panel in the browser. Turn it off for anything other people can reach.

Problem Fix
app.run_server raises an error It was replaced by app.run
"Duplicate callback outputs" Two callbacks write the same property. Merge them, or add allow_duplicate=True to the extra Output together with prevent_initial_call=True
"A nonexistent object was used in an Input..." An id in the callback isn't in the layout. Check spelling. For components created by other callbacks, set suppress_callback_exceptions=True
Callback runs before the user does anything Pass prevent_initial_call=True
Port 8050 is in use app.run(port=8051)
Leave one output unchanged Return dash.no_update for it

For sortable, filterable tables, install dash-ag-grid with pip install "dash[ag-grid]". The older dash_table.DataTable is deprecated in Dash 4.5.

Deploy a Dash App

app.run() starts a development server. In production, expose the underlying Flask server and run it with a WSGI server such as Gunicorn:

app = Dash()
server = app.server    # Gunicorn serves this object
pip install gunicorn
gunicorn app:server

Put dash, pandas, and gunicorn in requirements.txt and use that start command on a host such as Render, Railway, or your own server. Plotly's own hosting service, Plotly Cloud, is another option.

Dash or Streamlit?

Dash Streamlit
How it updates Only the callbacks whose inputs changed The whole script reruns
Amount of code More, since you wire up each interaction Less
Layout control Full HTML and CSS Columns, tabs, sidebar
Good fit Custom dashboards with linked charts Quick data apps and prototypes

See the same app built in Dash, Streamlit, Shiny, Gradio, and Panel, or your first Streamlit app.

Similar Topics