Python Guide
Build a Streamlit Dashboard in Python
Create a professional data dashboard with sidebars, KPIs, and interactive Plotly charts — all with pure Python.
Quick answer: Install streamlit pandas plotly, create an app.py file, add st.set_page_config(layout="wide"), build a sidebar with st.sidebar.selectbox(), display KPIs with st.metric() inside st.columns(), and render charts with st.plotly_chart(). Run with streamlit run app.py.
Install Dependencies
pip install streamlit pandas plotly
Create a project folder and a file called app.py:
mkdir streamlit-dashboard
cd streamlit-dashboard
touch app.py
💡 Tip: Create a requirements.txt file with these dependencies for easy deployment later.
Set Up Page Config and Imports
Start your app.py with these imports and page setup:
import streamlit as st
import pandas as pd
import plotly.express as px
# Page config MUST be the first Streamlit command
st.set_page_config(
page_title="Sales Dashboard",
page_icon="📊",
layout="wide",
initial_sidebar_state="expanded"
)
st.title("📊 Sales Analytics Dashboard")
st.markdown("Interactive dashboard built with Streamlit and Plotly.")
Important: st.set_page_config() must be the first Streamlit command in your script. Placing it after other st commands will throw an error.
Load Sample Data
For this tutorial, we'll generate sample sales data. In real apps, you'd load from a CSV, database, or API:
@st.cache_data
def load_data():
import numpy as np
np.random.seed(42)
dates = pd.date_range("2024-01-01", periods=180, freq="D")
regions = ["North", "South", "East", "West"]
data = pd.DataFrame({
"Date": np.repeat(dates, len(regions)),
"Region": regions * len(dates),
"Sales": np.random.randint(1000, 10000, len(dates) * len(regions)),
"Orders": np.random.randint(10, 200, len(dates) * len(regions))
})
return data
df = load_data()
💡 Why caching matters: @st.cache_data ensures the data loads only once, not every time a user interacts with the dashboard.
Build the Sidebar Filters
The sidebar keeps controls separate from visualizations:
st.sidebar.header("🔍 Filters")
# Date range filter
date_range = st.sidebar.date_input(
"Date range",
value=(df["Date"].min(), df["Date"].max()),
min_value=df["Date"].min(),
max_value=df["Date"].max()
)
# Region filter
selected_regions = st.sidebar.multiselect(
"Regions",
options=df["Region"].unique(),
default=df["Region"].unique()
)
# Apply filters
filtered_df = df[
(df["Date"] >= pd.to_datetime(date_range[0])) &
(df["Date"] <= pd.to_datetime(date_range[1])) &
(df["Region"].isin(selected_regions))
]
Display KPI Metrics
Use st.columns() and st.metric() for a clean KPI row:
total_sales = filtered_df["Sales"].sum()
total_orders = filtered_df["Orders"].sum()
avg_order = total_sales / total_orders if total_orders else 0
col1, col2, col3 = st.columns(3)
col1.metric("💰 Total Sales", f"${total_sales:,.0f}", "+12%")
col2.metric("📦 Total Orders", f"{total_orders:,}", "+5%")
col3.metric("📊 Avg Order Value", f"${avg_order:.2f}", "-2%")
The third argument is the delta indicator (the green/red arrow). Streamlit handles the styling automatically.
Add Plotly Charts
Plotly charts are interactive and look great on Streamlit. Add these below your KPIs:
# Line chart — Sales over time
st.subheader("📈 Sales Trend")
fig_line = px.line(
filtered_df.groupby("Date")["Sales"].sum().reset_index(),
x="Date", y="Sales",
title="Daily Sales"
)
st.plotly_chart(fig_line, use_container_width=True)
# Bar chart — Sales by Region
col_left, col_right = st.columns(2)
with col_left:
st.subheader("📍 Sales by Region")
fig_bar = px.bar(
filtered_df.groupby("Region")["Sales"].sum().reset_index(),
x="Region", y="Sales", color="Region"
)
st.plotly_chart(fig_bar, use_container_width=True)
with col_right:
st.subheader("🥧 Order Distribution")
fig_pie = px.pie(
filtered_df.groupby("Region")["Orders"].sum().reset_index(),
names="Region", values="Orders"
)
st.plotly_chart(fig_pie, use_container_width=True)
💡 Pro tip: use_container_width=True makes charts automatically resize to fit the screen. Always use it for responsive dashboards.
Run Your Dashboard
streamlit run app.py
Your browser opens at localhost:8501. You now have a fully interactive dashboard. Every time you change a filter, the entire dashboard updates automatically.
Deploy for Free
Deploy in under 5 minutes:
- Create a
requirements.txtfile withstreamlit,pandas, andplotly - Push your code to a GitHub repo
- Go to
share.streamlit.ioand connect your repo - Select
app.pyas the main file - Click Deploy
Bonus: Streamlit Community Cloud gives you a free URL like your-app.streamlit.app. Perfect for portfolios and internal tools.
🎯 Dashboard Layout Cheatsheet
| Layout Goal | Streamlit Command |
|---|---|
| Full-width layout | st.set_page_config(layout="wide") |
| Side-by-side columns | st.columns([1, 1]) |
| Sidebar controls | st.sidebar.widget() |
| Tabbed sections | st.tabs(["Tab 1", "Tab 2"]) |
| Expandable panels | st.expander("More details") |
🛡️ Best Practices for Streamlit Dashboards
- Always use
@st.cache_datafor data loading and@st.cache_resourcefor database connections - Keep the sidebar for filters and controls — never mix them with visualizations
- Use
use_container_width=Trueon all charts for responsive layouts - Group related metrics with
st.columns()— never stack more than 4 metrics in a row - Use
st.session_stateto persist user selections across reruns - Add
st.spinner()for any operation that takes longer than 1 second - Store API keys and DB credentials in
.streamlit/secrets.toml
Performance warning: Every widget interaction reruns the entire script. Without caching, loading a large dataset from a database on every interaction can slow your dashboard to a crawl.
❓ Frequently Asked Questions
Can I build a dashboard with Streamlit?
Yes. Streamlit is one of the most popular Python frameworks for building data dashboards. It handles layouts, widgets, and charts with pure Python.
Does Streamlit support Plotly charts?
Yes. Streamlit has native support for Plotly, Altair, Matplotlib, and Bokeh. Use st.plotly_chart() to render interactive Plotly figures.
How do I add filters to a Streamlit dashboard?
Use st.sidebar with widgets like st.selectbox, st.slider, or st.multiselect. The sidebar keeps controls separate from the main visualization area.
Can I connect a database to Streamlit?
Yes. You can connect Streamlit to PostgreSQL, MySQL, MongoDB, or any database using libraries like SQLAlchemy, psycopg2, or PyMongo. Wrap connections in @st.cache_resource.
Is Streamlit good for production dashboards?
Yes, for internal dashboards and data apps. For high-traffic public dashboards, consider adding authentication, caching, and hosting on a scalable platform.