Build interactive data applications and dashboards with pure Python - no frontend experience required
npx playbooks add skill vamseeachanta/workspace-hub --skill streamlit
Build beautiful, interactive data applications with pure Python. Transform data scripts into shareable web apps in minutes with widgets, charts, and layouts.
# Basic installation
pip install streamlit
# With common extras
pip install streamlit plotly pandas polars
# Using uv (recommended)
uv pip install streamlit plotly pandas polars altair
# Verify installation
streamlit hello
Minimal App (app.py):
import streamlit as st
import pandas as pd
import polars as pl
# Page configuration (must be first Streamlit command)
st.set_page_config(
page_title="My Data App",
page_icon="📊",
layout="wide",
initial_sidebar_state="expanded"
)
# Title and header
st.title("My Data Application")
st.header("Welcome to the Dashboard")
st.subheader("Data Analysis Section")
# Text elements
st.text("This is plain text")
st.markdown("**Bold** and *italic* text with [links](https://streamlit.io)")
st.caption("This is a caption for additional context")
st.code("print('Hello, Streamlit!')", language="python")
# Display data
df = pd.DataFrame({
"Name": ["Alice", "Bob", "Charlie"],
"Age": [25, 30, 35],
"City": ["NYC", "LA", "Chicago"]
})
st.dataframe(df) # Interactive table
st.table(df) # Static table
st.json({"key": "value", "list": [1, 2, 3]})
# Metrics
col1, col2, col3 = st.columns(3)
col1.metric("Revenue", "$1.2M", "+12%")
col2.metric("Users", "10,234", "-2%")
col3.metric("Conversion", "3.2%", "+0.5%")
Run the app:
streamlit run app.py
Input Widgets:
import streamlit as st
from datetime import datetime, date
# Text inputs
name = st.text_input("Enter your name", value="User")
bio = st.text_area("Tell us about yourself", height=100)
password = st.text_input("Password", type="password")
# Numeric inputs
age = st.number_input("Age", min_value=0, max_value=120, value=25, step=1)
price = st.slider("Price Range", 0.0, 100.0, (25.0, 75.0)) # Range slider
rating = st.slider("Rating", 1, 5, 3)
# Selection widgets
option = st.selectbox("Choose an option", ["Option A", "Option B", "Option C"])
options = st.multiselect("Select multiple", ["Red", "Green", "Blue"], default=["Red"])
radio_choice = st.radio("Pick one", ["Small", "Medium", "Large"], horizontal=True)
# Boolean inputs
agree = st.checkbox("I agree to the terms")
toggle = st.toggle("Enable feature")
# Date and time
selected_date = st.date_input("Select a date", value=date.today())
date_range = st.date_input(
"Date range",
value=(date(2025, 1, 1), date.today()),
format="YYYY-MM-DD"
)
selected_time = st.time_input("Select a time")
# File upload
uploaded_file = st.file_uploader("Upload a CSV file", type=["csv", "xlsx"])
if uploaded_file is not None:
df = pd.read_csv(uploaded_file)
st.write(f"Loaded {len(df)} rows")
# Color picker
color = st.color_picker("Pick a color", "#00FF00")
# Buttons
if st.button("Click me"):
st.write("Button clicked!")
# Download button
@st.cache_data
def get_data():
return pd.DataFrame({"x": [1, 2, 3], "y": [4, 5, 6]})
csv = get_data().to_csv(index=False)
st.download_button(
label="Download CSV",
data=csv,
file_name="data.csv",
mime="text/csv"
)
Columns:
import streamlit as st
# Equal columns
col1, col2, col3 = st.columns(3)
with col1:
st.header("Column 1")
st.write("Content for column 1")
with col2:
st.header("Column 2")
st.metric("Metric", "100")
with col3:
st.header("Column 3")
st.button("Action")
# Unequal columns
left, right = st.columns([2, 1]) # 2:1 ratio
with left:
st.write("Wider column")
with right:
st.write("Narrower column")
Sidebar:
import streamlit as st
# Sidebar content
st.sidebar.title("Navigation")
st.sidebar.header("Filters")
# Sidebar widgets
category = st.sidebar.selectbox("Category", ["All", "A", "B", "C"])
min_value = st.sidebar.slider("Minimum Value", 0, 100, 25)
show_raw = st.sidebar.checkbox("Show raw data")
# Using 'with' syntax
with st.sidebar:
st.header("Settings")
theme = st.radio("Theme", ["Light", "Dark"])
st.divider()
st.caption("App v1.0.0")
Tabs:
import streamlit as st
tab1, tab2, tab3 = st.tabs(["📈 Chart", "📊 Data", "⚙️ Settings"])
with tab1:
st.header("Chart View")
# Add chart here
with tab2:
st.header("Data View")
# Add dataframe here
with tab3:
st.header("Settings")
# Add settings here
Expanders and Containers:
import streamlit as st
# Expander (collapsible section)
with st.expander("Click to expand"):
st.write("Hidden content revealed!")
st.code("print('Hello')")
# Container (grouping elements)
with st.container():
st.write("This is inside a container")
col1, col2 = st.columns(2)
col1.write("Left")
col2.write("Right")
# Container with border
with st.container(border=True):
st.write("Content with border")
# Empty placeholder (for dynamic updates)
placeholder = st.empty()
placeholder.text("Initial text")
# Later: placeholder.text("Updated text")
Plotly Integration:
import streamlit as st
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
# Sample data
df = pd.DataFrame({
"date": pd.date_range("2025-01-01", periods=100),
"value": [i + (i % 7) * 5 for i in range(100)],
"category": ["A", "B", "C", "D"] * 25
})
# Plotly Express charts
fig = px.line(df, x="date", y="value", color="category", title="Time Series")
st.plotly_chart(fig, use_container_width=True)
# Scatter plot
fig_scatter = px.scatter(
df, x="date", y="value",
color="category", size="value",
hover_data=["category"]
)
st.plotly_chart(fig_scatter, use_container_width=True)
# Bar chart
category_totals = df.groupby("category")["value"].sum().reset_index()
fig_bar = px.bar(category_totals, x="category", y="value", title="Category Totals")
st.plotly_chart(fig_bar, use_container_width=True)
# Graph Objects for more control
fig_go = go.Figure()
fig_go.add_trace(go.Scatter(
x=df["date"],
y=df["value"],
mode="lines+markers",
name="Values"
))
fig_go.update_layout(title="Custom Plotly Chart", hovermode="x unified")
st.plotly_chart(fig_go, use_container_width=True)
Built-in Charts:
import streamlit as st
import pandas as pd
import numpy as np
# Sample data
chart_data = pd.DataFrame(
np.random.randn(20, 3),
columns=["A", "B", "C"]
)
# Simple line chart
st.line_chart(chart_data)
# Area chart
st.area_chart(chart_data)
# Bar chart
st.bar_chart(chart_data)
# Scatter chart (Streamlit 1.26+)
scatter_data = pd.DataFrame({
"x": np.random.randn(100),
"y": np.random.randn(100),
"size": np.random.rand(100) * 100
})
st.scatter_chart(scatter_data, x="x", y="y", size="size")
# Map
map_data = pd.DataFrame({
"lat": np.random.randn(100) / 50 + 37.76,
"lon": np.random.randn(100) / 50 - 122.4
})
st.map(map_data)
Matplotlib Integration:
import streamlit as st
import matplotlib.pyplot as plt
import numpy as np
# Create matplotlib figure
fig, ax = plt.subplots(figsize=(10, 6))
x = np.linspace(0, 10, 100)
ax.plot(x, np.sin(x), label="sin(x)")
ax.plot(x, np.cos(x), label="cos(x)")
ax.legend()
ax.set_title("Matplotlib Chart")
# Display in Streamlit
st.pyplot(fig)
Cache Data (for expensive data operations):
import streamlit as st
import pandas as pd
import polars as pl
import time
@st.cache_data
def load_data(file_path: str) -> pd.DataFrame:
"""Load and cache data. Cache key: file_path."""
time.sleep(2) # Simulate slow load
return pd.read_csv(file_path)
@st.cache_data(ttl=3600) # Cache expires after 1 hour
def fetch_api_data(endpoint: str) -> dict:
"""Fetch data from API with time-based cache."""
import requests
response = requests.get(endpoint)
return response.json()
@st.cache_data(show_spinner="Loading data...")
def load_with_spinner(path: str) -> pl.DataFrame:
"""Show custom spinner while loading."""
return pl.read_parquet(path)
# Using cached functions
df = load_data("data/sales.csv") # First call: slow
df = load_data("data/sales.csv") # Second call: instant (cached)
# Clear cache programmatically
if st.button("Clear cache"):
st.cache_data.clear()
Cache Resources (for global resources):
import streamlit as st
from sqlalchemy import create_engine
@st.cache_resource
def get_database_connection():
"""Cache database connection (singleton pattern)."""
return create_engine("postgresql://user:pass@localhost/db")
@st.cache_resource
def load_ml_model():
"""Cache ML model (loaded once per session)."""
import joblib
return joblib.load("model.pkl")
# Use cached resources
engine = get_database_connection()
model = load_ml_model()
Managing State:
import streamlit as st
# Initialize state
if "counter" not in st.session_state:
st.session_state.counter = 0
if "messages" not in st.session_state:
st.session_state.messages = []
# Display current state
st.write(f"Counter: {st.session_state.counter}")
# Update state with buttons
col1, col2, col3 = st.columns(3)
if col1.button("Increment"):
st.session_state.counter += 1
st.rerun()
if col2.button("Decrement"):
st.session_state.counter -= 1
st.rerun()
if col3.button("Reset"):
st.session_state.counter = 0
st.rerun()
# State with widgets
st.text_input("Name", key="user_name")
st.write(f"Hello, {st.session_state.user_name}!")
# State callback
def on_change():
st.session_state.processed = st.session_state.raw_input.upper()
st.text_input("Raw input", key="raw_input", on_change=on_change)
if "processed" in st.session_state:
st.write(f"Processed: {st.session_state.processed}")
Form State:
import streamlit as st
# Forms prevent rerunning on every widget change
with st.form("my_form"):
st.write("Submit all at once:")
name = st.text_input("Name")
age = st.number_input("Age", min_value=0, max_value=120)
color = st.selectbox("Favorite color", ["Red", "Green", "Blue"])
# Every form needs a submit button
submitted = st.form_submit_button("Submit")
if submitted:
st.success(f"Thanks {name}! You're {age} and like {color}.")
Directory Structure:
my_app/
├── app.py # Main entry point (optional)
├── pages/
│ ├── 1_📊_Dashboard.py
│ ├── 2_📈_Analytics.py
│ └── 3_⚙️_Settings.py
└── utils/
└── helpers.py
Main App (app.py):
import streamlit as st
st.set_page_config(
page_title="Multi-Page App",
page_icon="🏠",
layout="wide"
)
st.title("Welcome to My App")
st.write("Use the sidebar to navigate between pages.")
# Shared state initialization
if "user" not in st.session_state:
st.session_state.user = None
Page 1 (pages/1_Dashboard.py):
import streamlit as st
st.set_page_config(page_title="Dashboard", page_icon="📊")
st.title("📊 Dashboard")
st.write("This is the dashboard page")
# Access shared state
if st.session_state.get("user"):
st.write(f"Welcome back, {st.session_state.user}!")
Page 2 (pages/2_Analytics.py):
import streamlit as st
st.set_page_config(page_title="Analytics", page_icon="📈")
st.title("📈 Analytics")
st.write("This is the analytics page")
# Add analytics content
Status and Progress:
import streamlit as st
import time
# Progress bar
progress = st.progress(0, text="Processing...")
for i in range(100):
time.sleep(0.01)
progress.progress(i + 1, text=f"Processing... {i+1}%")
# Spinner
with st.spinner("Loading data..."):
time.sleep(2)
st.success("Done!")
# Status messages
st.success("Operation successful!")
st.info("This is informational")
st.warning("Warning: Check your inputs")
st.error("An error occurred")
st.exception(ValueError("Example exception"))
# Toast notifications
st.toast("Data saved!", icon="✅")
# Balloons and snow
st.balloons()
st.snow()
Chat Interface:
import streamlit as st
import time
st.title("Chat Demo")
# Initialize chat history
if "messages" not in st.session_state:
st.session_state.messages = []
# Display chat history
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Chat input
if prompt := st.chat_input("What's on your mind?"):
# Add user message
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
# Generate response
with st.chat_message("assistant"):
response = f"You said: {prompt}"
st.markdown(response)
st.session_state.messages.append({"role": "assistant", "content": response})
Data Editor:
import streamlit as st
import pandas as pd
# Editable dataframe
df = pd.DataFrame({
"Name": ["Alice", "Bob", "Charlie"],
"Age": [25, 30, 35],
"Active": [True, False, True]
})
edited_df = st.data_editor(
df,
num_rows="dynamic", # Allow adding/deleting rows
column_config={
"Name": st.column_config.TextColumn("Name", required=True),
"Age": st.column_config.NumberColumn("Age", min_value=0, max_value=120),
"Active": st.column_config.CheckboxColumn("Active")
}
)
if st.button("Save changes"):
st.write("Saved:", edited_df)
import streamlit as st
import pandas as pd
import polars as pl
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, timedelta
# Page config
st.set_page_config(
page_title="Sales Dashboard",
page_icon="📊",
layout="wide"
)
# Custom CSS
st.markdown("""
<style>
.metric-card {
background-color: #f0f2f6;
padding: 20px;
border-radius: 10px;
text-align: center;
}
</style>
""", unsafe_allow_html=True)
# Title
st.title("📊 Sales Analytics Dashboard")
# Sidebar filters
st.sidebar.header("Filters")
# Date range filter
date_range = st.sidebar.date_input(
"Date Range",
value=(datetime.now() - timedelta(days=30), datetime.now()),
format="YYYY-MM-DD"
)
# Category filter
categories = st.sidebar.multiselect(
"Categories",
options=["Electronics", "Clothing", "Food", "Home", "Sports"],
default=["Electronics", "Clothing", "Food"]
)
# Region filter
regions = st.sidebar.multiselect(
"Regions",
options=["North", "South", "East", "West"],
default=["North", "South", "East", "West"]
)
# Load and filter data
@st.cache_data
def load_sales_data():
"""Generate sample sales data."""
import numpy as np
np.random.seed(42)
dates = pd.date_range(start="2024-01-01", end="2025-12-31", freq="D")
n = len(dates) * 10 # Multiple records per day
return pd.DataFrame({
"date": np.random.choice(dates, n),
"category": np.random.choice(
["Electronics", "Clothing", "Food", "Home", "Sports"], n
),
"region": np.random.choice(["North", "South", "East", "West"], n),
"revenue": np.random.uniform(100, 5000, n),
"units": np.random.randint(1, 50, n),
"customer_id": np.random.randint(1000, 9999, n)
})
# Load data
df = load_sales_data()
# Apply filters
filtered_df = df[
(df["date"] >= pd.Timestamp(date_range[0])) &
(df["date"] <= pd.Timestamp(date_range[1])) &
(df["category"].isin(categories)) &
(df["region"].isin(regions))
]
# KPI Metrics Row
st.subheader("Key Performance Indicators")
col1, col2, col3, col4 = st.columns(4)
total_revenue = filtered_df["revenue"].sum()
total_units = filtered_df["units"].sum()
total_orders = len(filtered_df)
unique_customers = filtered_df["customer_id"].nunique()
col1.metric(
"Total Revenue",
f"${total_revenue:,.0f}",
delta=f"+{(total_revenue * 0.12):,.0f} vs last period"
)
col2.metric(
"Units Sold",
f"{total_units:,}",
delta=f"+{int(total_units * 0.08):,}"
)
col3.metric(
"Orders",
f"{total_orders:,}",
delta=f"+{int(total_orders * 0.05):,}"
)
col4.metric(
"Unique Customers",
f"{unique_customers:,}",
delta=f"+{int(unique_customers * 0.03):,}"
)
# Charts Row
st.subheader("Revenue Analysis")
col1, col2 = st.columns(2)
with col1:
# Revenue trend
daily_revenue = filtered_df.groupby("date")["revenue"].sum().reset_index()
fig_trend = px.line(
daily_revenue,
x="date",
y="revenue",
title="Daily Revenue Trend"
)
fig_trend.update_layout(hovermode="x unified")
st.plotly_chart(fig_trend, use_container_width=True)
with col2:
# Revenue by category
category_revenue = filtered_df.groupby("category")["revenue"].sum().reset_index()
fig_category = px.pie(
category_revenue,
values="revenue",
names="category",
title="Revenue by Category"
)
st.plotly_chart(fig_category, use_container_width=True)
# Second charts row
col1, col2 = st.columns(2)
with col1:
# Regional comparison
regional_data = filtered_df.groupby("region").agg({
"revenue": "sum",
"units": "sum"
}).reset_index()
fig_region = px.bar(
regional_data,
x="region",
y="revenue",
color="region",
title="Revenue by Region"
)
st.plotly_chart(fig_region, use_container_width=True)
with col2:
# Category by region heatmap
pivot_data = filtered_df.pivot_table(
values="revenue",
index="category",
columns="region",
aggfunc="sum"
)
fig_heatmap = px.imshow(
pivot_data,
title="Revenue Heatmap: Category vs Region",
color_continuous_scale="Blues",
text_auto=".0f"
)
st.plotly_chart(fig_heatmap, use_container_width=True)
# Data Table
st.subheader("Detailed Data")
with st.expander("View Raw Data"):
# Aggregated summary
summary = filtered_df.groupby(["date", "category", "region"]).agg({
"revenue": "sum",
"units": "sum",
"customer_id": "nunique"
}).reset_index()
summary.columns = ["Date", "Category", "Region", "Revenue", "Units", "Customers"]
st.dataframe(
summary.sort_values("Date", ascending=False),
use_container_width=True,
height=400
)
# Download button
csv = summary.to_csv(index=False)
st.download_button(
label="Download CSV",
data=csv,
file_name=f"sales_data_{datetime.now().strftime('%Y%m%d')}.csv",
mime="text/csv"
)
# Footer
st.markdown("---")
st.caption(f"Last updated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
import streamlit as st
import pandas as pd
import polars as pl
import plotly.express as px
st.sWeekly roundup of top Claude Code skills, MCP servers, and AI coding tips.