Python Tutorial
Dash Graphs
dcc.Graph displays a Plotly figure. Build the figure in a callback from Pandas data.
Plotly Express in a Callback
from dash import Dash, dcc, html, Input, Output, callback
import plotly.express as px
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Oslo", "Bergen", "Bergen"],
"month": [1, 2, 1, 2],
"signups": [12, 18, 9, 14],
})
app = Dash(__name__)
app.layout = html.Div([
dcc.Dropdown(
id="city",
options=sorted(df["city"].unique()),
value="Oslo",
),
dcc.Graph(id="chart"),
])
@callback(Output("chart", "figure"), Input("city", "value"))
def draw(city):
subset = df[df["city"] == city]
return px.bar(subset, x="month", y="signups", title=city)
if __name__ == "__main__":
app.run(debug=True)📘 Real-World Deep Dive
Knowing <strong>Dash Graphs (Dash)</strong> well is what turns Dash from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of Dash Graphs that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
import plotly.express as px
from dash import dcc
import pandas as pd
df = pd.DataFrame({"x":[1,2,3,4], "y":[10,11,12,13]})
graph = dcc.Graph(figure=px.line(df, x="x", y="y"))Expected Output
(no output)Common mistakes
- Callbacks must declare
Output/Input/Statein the right order; mismatched component IDs silently produce empty updates. @app.callbackbody cannot read HTML — return only data, render in the layout.- Each request lifecycle can fire callbacks many times — debounce heavy computation with
dcc.Intervalor caching. - Treating Dash Graphs as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- Use
functools.lru_cacheon expensive data-loaders prefixed by their inputs. - Switch large tables to
dash_table.DataTablewithvirtualization=True. - Run in production with
gunicorn --workers 4 --threads 8and proxy through nginx. - When working with Dash, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.