Build Project

Learn by Building

Home › Build Projects › Python Apps › Streamlit Dashboard

Python App · Beginner-Intermediate

Build a Streamlit Dashboard

An interactive data dashboard in pure Python. Sales metrics, filters, charts, and a live demo — no JavaScript, no HTML, no frontend code.

⏱️ 60 minutes · 📄 1 file · 🎯 Intermediate

What you'll build: A sales dashboard where you can filter by region, see revenue trends, compare products, and view key metrics — all driven by Python code and Streamlit components.

What you'll learn: st.cache_data, st.columns, st.metric, st.dataframe, st.plotly_chart, st.sidebar, and the Streamlit re-run model. These cover 90% of real Streamlit work.

Sales Dashboard · Streamlit
Total Revenue
$842,391
Orders
12,847
Avg Order
$65.58
Revenue by Month

📋 Before you start

You need Python 3.9+ installed. Check with:

python --version
# Should print Python 3.9 or higher

pip --version
# Should print pip 21 or higher

If you don't have Python, install it from python.org or your OS package manager.

1

Install Streamlit and dependencies

Everything you need is in three packages.

pip install streamlit pandas plotly

What each does:

  • streamlit — the framework
  • pandas — data manipulation
  • plotly — interactive charts (Streamlit's built-in charts are static)

Pro tip: Use a virtual environment to keep dependencies isolated: python -m venv .venv then activate it before installing.

2

Create the project file

Streamlit apps live in a single Python file. No project structure needed.

mkdir streamlit-dashboard
cd streamlit-dashboard

# Create the main file
touch app.py

Everything goes in app.py.

3

Generate sample data

Real projects load data from a database or API. For this tutorial, we'll generate realistic sales data so the app works out of the box.

app.py
import streamlit as st
import pandas as pd
import plotly.express as px
import numpy as np
from datetime import date, timedelta

# Page config — MUST be the first Streamlit command
st.set_page_config(
    page_title="Sales Dashboard",
    page_icon="📊",
    layout="wide"
)

@st.cache_data
def generate_sales_data():
    """Generate realistic sample sales data. Cached so it doesn't rebuild on every interaction."""
    np.random.seed(42)
    regions = ["North", "South", "East", "West"]
    products = ["Widget", "Gadget", "Gizmo", "Doohickey"]
    n_rows = 500

    start = date(2026, 1, 1)
    dates = [start + timedelta(days=int(x)) for x in np.random.randint(0, 365, n_rows)]

    df = pd.DataFrame({
        "date": dates,
        "region": np.random.choice(regions, n_rows),
        "product": np.random.choice(products, n_rows),
        "quantity": np.random.randint(1, 20, n_rows),
        "price": np.round(np.random.uniform(10, 200, n_rows), 2),
    })

    df["revenue"] = df["quantity"] * df["price"]
    return df

df = generate_sales_data()

Why @st.cache_data? Streamlit re-runs the entire script on every input change. Without caching, this data regenerates 500 rows every time you click a filter — slow and inconsistent. With caching, it's built once and reused.

4

Build the sidebar filters

The sidebar is where user controls go. Filters update the data behind the scenes.

app.py (add after data)
# SIDEBAR
with st.sidebar:
    st.header("🔍 Filters")

    selected_regions = st.multiselect(
        "Regions",
        options=df["region"].unique(),
        default=df["region"].unique()
    )

    selected_products = st.multiselect(
        "Products",
        options=df["product"].unique(),
        default=df["product"].unique()
    )

    date_range = st.date_input(
        "Date range",
        value=(df["date"].min(), df["date"].max()),
        min_value=df["date"].min(),
        max_value=df["date"].max()
    )

# Apply filters
filtered = df[
    df["region"].isin(selected_regions)
    & df["product"].isin(selected_products)
    & (df["date"] >= date_range[0])
    & (df["date"] <= date_range[1])
]

st.sidebar.caption(f"Showing {len(filtered):,} of {len(df):,} records")

Pro tip: When a filter is empty (user deselects everything), filtered becomes an empty DataFrame. Always check if filtered.empty: before displaying metrics — we'll handle this in the next step.

5

Add the KPI metrics

The top of the dashboard shows the numbers that matter. st.columns lays them out side by side.

app.py (add after filters)
# MAIN CONTENT
st.title("📊 Sales Dashboard")
st.caption("Sample data · Last updated 2026")

if filtered.empty:
    st.warning("No data matches your filters. Try widening the range.")
    st.stop()

# KPI row
col1, col2, col3, col4 = st.columns(4)

with col1:
    st.metric(
        "Total Revenue",
        f"${filtered['revenue'].sum():,.0f}",
        delta=f"{((filtered['revenue'].sum() / df['revenue'].sum()) * 100):.1f}% of total"
    )

with col2:
    st.metric(
        "Orders",
        f"{len(filtered):,}",
        delta=None
    )

with col3:
    st.metric(
        "Avg Order Value",
        f"${filtered['revenue'].mean():,.2f}",
        delta=None
    )

with col4:
    st.metric(
        "Avg Quantity",
        f"{filtered['quantity'].mean():.1f}",
        delta=None
    )

Pro tip: st.stop() halts the script. This is how you handle the "empty filter" case gracefully — the rest of the dashboard never renders when there's nothing to show.

6

Add the charts

Two charts: revenue over time and revenue by region. Both are interactive Plotly charts.

app.py (add after KPIs)
# Charts row
chart_col1, chart_col2 = st.columns(2)

with chart_col1:
    st.subheader("Revenue Over Time")
    daily = (
        filtered.groupby("date", as_index=False)["revenue"]
        .sum()
        .sort_values("date")
    )
    fig = px.line(
        daily,
        x="date",
        y="revenue",
        markers=True,
        color_discrete_sequence=["#ff4b4b"]
    )
    fig.update_layout(
        margin=dict(l=0, r=0, t=10, b=0),
        height=350,
        xaxis_title="",
        yaxis_title="Revenue ($)"
    )
    st.plotly_chart(fig, use_container_width=True)

with chart_col2:
    st.subheader("Revenue by Region")
    by_region = (
        filtered.groupby("region", as_index=False)["revenue"]
        .sum()
        .sort_values("revenue", ascending=False)
    )
    fig = px.bar(
        by_region,
        x="region",
        y="revenue",
        color="region",
        color_discrete_sequence=["#ff4b4b", "#f59e0b", "#22c55e", "#3b82f6"]
    )
    fig.update_layout(
        margin=dict(l=0, r=0, t=10, b=0),
        height=350,
        showlegend=False,
        xaxis_title="",
        yaxis_title="Revenue ($)"
    )
    st.plotly_chart(fig, use_container_width=True)
7

Add the data table

At the bottom, a sortable table showing every row. This is st.dataframe — Streamlit's interactive data grid.

app.py (add after charts)
st.subheader("📋 All Records")
st.caption("Click any column header to sort. Use the search box to filter.")

st.dataframe(
    filtered[["date", "region", "product", "quantity", "price", "revenue"]],
    use_container_width=True,
    hide_index=True,
    column_config={
        "revenue": st.column_config.NumberColumn(
            "Revenue",
            format="$%.2f"
        ),
        "price": st.column_config.NumberColumn(
            "Unit Price",
            format="$%.2f"
        ),
        "date": st.column_config.DateColumn(
            "Date",
            format="YYYY-MM-DD"
        )
    }
)

Pro tip: column_config is how you format columns in st.dataframe. Without it, prices show as raw numbers. With it, they render as $123.45 — instantly more professional.

8

Run it

One command starts the app. It opens in your browser at localhost:8501.

streamlit run app.py

What you should see:

  • A dark sidebar with three filters
  • Four KPI cards at the top
  • Two charts side-by-side
  • A sortable data table at the bottom
  • The whole page re-renders when you change a filter

Note: The first run may take 10–15 seconds to start. Streamlit is downloading fonts and setting up the local server. Subsequent runs are instant.

📄 Complete app.py

Copy this whole file if you don't want to paste the steps individually.

import streamlit as st
import pandas as pd
import plotly.express as px
import numpy as np
from datetime import date, timedelta

st.set_page_config(
    page_title="Sales Dashboard",
    page_icon="📊",
    layout="wide"
)

@st.cache_data
def generate_sales_data():
    np.random.seed(42)
    regions = ["North", "South", "East", "West"]
    products = ["Widget", "Gadget", "Gizmo", "Doohickey"]
    n_rows = 500

    start = date(2026, 1, 1)
    dates = [start + timedelta(days=int(x)) for x in np.random.randint(0, 365, n_rows)]

    df = pd.DataFrame({
        "date": dates,
        "region": np.random.choice(regions, n_rows),
        "product": np.random.choice(products, n_rows),
        "quantity": np.random.randint(1, 20, n_rows),
        "price": np.round(np.random.uniform(10, 200, n_rows), 2),
    })
    df["revenue"] = df["quantity"] * df["price"]
    return df

df = generate_sales_data()

# SIDEBAR
with st.sidebar:
    st.header("🔍 Filters")
    selected_regions = st.multiselect(
        "Regions",
        options=df["region"].unique(),
        default=df["region"].unique()
    )
    selected_products = st.multiselect(
        "Products",
        options=df["product"].unique(),
        default=df["product"].unique()
    )
    date_range = st.date_input(
        "Date range",
        value=(df["date"].min(), df["date"].max()),
        min_value=df["date"].min(),
        max_value=df["date"].max()
    )

filtered = df[
    df["region"].isin(selected_regions)
    & df["product"].isin(selected_products)
    & (df["date"] >= date_range[0])
    & (df["date"] <= date_range[1])
]

st.sidebar.caption(f"Showing {len(filtered):,} of {len(df):,} records")

# MAIN
st.title("📊 Sales Dashboard")
st.caption("Sample data · Last updated 2026")

if filtered.empty:
    st.warning("No data matches your filters. Try widening the range.")
    st.stop()

col1, col2, col3, col4 = st.columns(4)
with col1:
    st.metric("Total Revenue", f"${filtered['revenue'].sum():,.0f}",
              delta=f"{((filtered['revenue'].sum() / df['revenue'].sum()) * 100):.1f}% of total")
with col2:
    st.metric("Orders", f"{len(filtered):,}")
with col3:
    st.metric("Avg Order Value", f"${filtered['revenue'].mean():,.2f}")
with col4:
    st.metric("Avg Quantity", f"{filtered['quantity'].mean():.1f}")

chart_col1, chart_col2 = st.columns(2)
with chart_col1:
    st.subheader("Revenue Over Time")
    daily = filtered.groupby("date", as_index=False)["revenue"].sum().sort_values("date")
    fig = px.line(daily, x="date", y="revenue", markers=True, color_discrete_sequence=["#ff4b4b"])
    fig.update_layout(margin=dict(l=0, r=0, t=10, b=0), height=350, xaxis_title="", yaxis_title="Revenue ($)")
    st.plotly_chart(fig, use_container_width=True)

with chart_col2:
    st.subheader("Revenue by Region")
    by_region = filtered.groupby("region", as_index=False)["revenue"].sum().sort_values("revenue", ascending=False)
    fig = px.bar(by_region, x="region", y="revenue", color="region",
                 color_discrete_sequence=["#ff4b4b", "#f59e0b", "#22c55e", "#3b82f6"])
    fig.update_layout(margin=dict(l=0, r=0, t=10, b=0), height=350, showlegend=False,
                      xaxis_title="", yaxis_title="Revenue ($)")
    st.plotly_chart(fig, use_container_width=True)

st.subheader("📋 All Records")
st.caption("Click any column header to sort.")

st.dataframe(
    filtered[["date", "region", "product", "quantity", "price", "revenue"]],
    use_container_width=True,
    hide_index=True,
    column_config={
        "revenue": st.column_config.NumberColumn("Revenue", format="$%.2f"),
        "price": st.column_config.NumberColumn("Unit Price", format="$%.2f"),
        "date": st.column_config.DateColumn("Date", format="YYYY-MM-DD")
    }
)

⚠️ Common problems

streamlit: command not found

Streamlit isn't installed or isn't on your PATH. Run pip install streamlit again. If it still fails, use python -m streamlit run app.py.

Port 8501 is already in use

Another Streamlit app is running. Either close it, or run on a different port: streamlit run app.py --server.port 8502

Date filter throws "comparison error"

When the user picks a single date, st.date_input returns a tuple of length 1, not 2. Guard: if len(date_range) == 2: before unpacking.

Charts don't update when filter changes

You're probably using @st.cache_data on a function that takes filtered data. Don't cache the filter step — cache the data source only. Filters run fresh every time.

App is slow on first load

Normal. Streamlit downloads fonts and initializes the WebSocket connection. Subsequent reruns are instant. If it's slow on every rerun, you're missing @st.cache_data on an expensive function.

🎯 What to add next

🧠 How Streamlit actually works

This trips up every beginner. Worth 60 seconds.

1. Every interaction reruns the whole script

Click a filter, move a slider, type in a text input — the entire app.py runs from the top. This is called the "re-run model."

2. State lives in the browser session

Streamlit uses WebSockets to sync your Python process with the browser. Every rerun rebuilds the page from scratch. That's why st.cache_data matters — it prevents expensive work from repeating.

3. Layout is declarative, not imperative

You call st.columns(4) and then use those columns as context managers (with col1:). Everything inside renders into that column. No HTML, no CSS, no manual DOM.

4. Widgets return their current value

st.multiselect() returns a list. st.slider() returns a number. st.checkbox() returns a bool. Use the return value directly — no event handlers.

❓ Frequently asked questions

What is Streamlit?

Streamlit is a Python library for building interactive web apps with pure Python. You write Python, it handles the HTML, CSS, and JavaScript. No frontend knowledge required.

How long does this Streamlit dashboard take to build?

About 60 minutes if you copy-paste and follow along. Longer if you type every line carefully. The core concepts (st.cache_data, st.columns, st.metric, st.plotly_chart) are worth slowing down for.

Do I need frontend experience?

No. Streamlit handles all the UI. You just need Python knowledge and a working Streamlit installation. The tutorial includes the install commands.

Can I deploy a Streamlit dashboard for free?

Yes. Streamlit Community Cloud (share.streamlit.io) is free for public apps. It connects to your GitHub repo and auto-deploys on push. Netlify and Vercel don't work for Streamlit — they're for static sites.

Why does my Streamlit app reload on every input change?

Streamlit re-runs the entire script top-to-bottom on every interaction. That's the design. Use st.cache_data on expensive operations (data loading, API calls) so they don't re-run every time.

What is the difference between st.cache_data and st.cache_resource?

Use st.cache_data for serializable values like DataFrames and query results. Use st.cache_resource for global singletons like database connections or ML models. The wrong one causes subtle bugs.

🔗 Related

← All Build Projects