Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 42 ยท Dash and Deployment

Your First Dash App

Build your first Dash web app in pure Python: install Dash, write a layout with html and dcc components, show a Plotly figure in dcc.Graph, style it and run it locally.

Everything so far produced charts. A chart is a picture; an app is a page where people choose, filter and explore. Dash is the framework from the Plotly team that turns Python code and Plotly figures into interactive web apps, with no JavaScript, HTML or CSS required to get started. You write a layout (what the page contains) and callbacks (how it reacts), and Dash does the rest.

Dash apps are used for internal dashboards, scientific tools, data-labeling interfaces and live monitoring. In this lesson you build the layout part; the next lesson, Dash callbacks and live graphs, makes it interactive.

Dash needs a web server process, so the examples that call app.run() are shown read-only. The runnable examples on this page use the real Dash library inside your browser, but instead of starting a server they talk to the app through Flask's built-in test client, which is exactly how you would test an app on your own machine. The first run downloads Dash and a few dependencies, which can take half a minute.

Install and the smallest app

On your own computer:

Terminal
pip install dash pandas

Then create app.py:

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

df = px.data.gapminder().query("year == 2007")
fig = px.scatter(df, x="gdpPercap", y="lifeExp", size="pop", color="continent", log_x=True)

app = Dash(__name__)
app.layout = html.Div([
    html.H1("Wealth and health in 2007"),
    dcc.Graph(figure=fig),
])

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

Run python app.py and open http://127.0.0.1:8050. With debug=True, Dash reloads the page whenever you save the file and shows errors in the browser. That is all there is to a first app: a Dash object, an app.layout and a figure inside a dcc.Graph.

Components: html, dcc and more

A Dash layout is a tree of components, written as nested Python calls. Each component is an object with properties. There are three main families:

Package Purpose Examples
dash.html Every HTML tag html.Div, html.H1, html.P, html.Ul, html.Img, html.Button
dash.dcc Interactive controls and graphs dcc.Graph, dcc.Dropdown, dcc.Slider, dcc.RadioItems, dcc.DatePickerRange, dcc.Store, dcc.Interval
dash.dash_table Editable data tables dash_table.DataTable

Third-party packages add more: dash-bootstrap-components (a Bootstrap layout grid and widgets), dash-mantine-components, dash-ag-grid (a spreadsheet-like grid) and dash-leaflet (maps).

The first positional argument of most html components is children: a string, a component or a list of components. Other properties mirror HTML: id, className, style (a dictionary using camelCase keys such as backgroundColor), and so on.

Python Build a layout and inspect it (real 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.

The tree shows how a layout is structured, and the last lines show what a browser would receive: Dash serves the layout as JSON from /_dash-layout, and a small React app in the browser turns it into the page. The browser does the rendering, and Python is only asked for the layout and for callback results.

Styling

Four ways, from quick to scalable:

  1. style={...} on a component: fine for one-off tweaks.
  2. className with a stylesheet. Any .css file placed in an assets/ folder next to app.py is loaded automatically, so you can write ordinary CSS with className="card".
  3. External stylesheets: Dash(__name__, external_stylesheets=[dbc.themes.FLATLY]) with Bootstrap components gives a responsive grid (dbc.Row, dbc.Col) and ready-made cards, navbars and forms.
  4. Plotly figure templates for charts (template="plotly_white") so figure and page match. Set dcc.Graph(style={"height": "60vh"}) so a graph fills part of the screen.

Also in assets/: images, a favicon.ico and extra JavaScript. Dash serves the folder under /assets/.

Project layout for real apps

An app grows. A common structure that keeps files small:

TEXT
my_dash_app/
  app.py              # creates Dash(), assembles the layout, starts the server
  layouts.py          # functions returning parts of the page
  callbacks.py        # all @app.callback functions
  data.py             # loading and cleaning data (once, at import)
  assets/style.css
  requirements.txt

For apps with several pages Dash has a pages feature: put one file per page in a pages/ folder, call dash.register_page(__name__, path="/sales") in each, set Dash(__name__, use_pages=True) and place dash.page_container in the layout. The URL then selects the page, so links and the back button work.

Layout is evaluated when? Static versus dynamic

app.layout can be a function. If you assign the function itself (without calling it), Dash calls it on every page load, so each user session sees fresh data, such as today's date or the newest rows from a database. If you assign a ready-made value, the layout is created once at start-up, which is faster. Choose a function for data that changes, a value for data that does not.

Python
def serve_layout():
    return html.Div([html.H1("Report"), html.P(f"Built at {pd.Timestamp.now():%H:%M}")])

app.layout = serve_layout     # no parentheses

How a Dash app works

sequenceDiagram
    participant B as Browser (React)
    participant S as Flask server
    participant P as Your Python code
    B->>S: GET /
    S-->>B: HTML shell and JavaScript
    B->>S: GET /_dash-layout
    S->>P: layout (or the layout function)
    P-->>B: JSON component tree
    B-->>B: renders the page

The layout is data. Callbacks (next lesson) add a second kind of request.

Common beginner mistakes

  • Forgetting children nesting. A Div takes a list; a missing comma between components gives a confusing error.
  • Duplicate ids. Every id must be unique in the app, because callbacks find components by id.
  • Calling the layout function. app.layout = serve_layout() freezes the page at start-up.
  • Mixing html.Div(style=...) keys in CSS form. Use camelCase: {"backgroundColor": "white"}.
  • Running with debug=True in production. See deploying Plotly apps.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is app.layout in a Dash app?

    The layout is a nested structure of html and dcc components that Dash sends to the browser as JSON.
  2. 2. Which component shows a Plotly figure?

    dcc.Graph takes a figure (or a figure dictionary) and renders it with Plotly.js.
  3. 3. Where does Dash automatically load CSS files from?

    Any .css or .js file in assets/ is included, and other files there are served under /assets/.
  4. 4. What happens if you set app.layout = serve_layout (a function, without parentheses)?

    A callable layout is evaluated for each new page load, which is useful for data that changes.

Summary

  • Dash turns Python into a web app: a Dash object, a layout, and (next) callbacks.
  • Layouts are trees of html, dcc and third-party components; the browser renders them from JSON.
  • dcc.Graph shows any Plotly figure; style with style, className, assets/ and Bootstrap.
  • Use a layout function for fresh data per page load; use pages/ for multi-page apps.
  • Run with python app.py; debug mode reloads on save, but is for development only.

Next: Dash Callbacks and Live Graphs