By the end of this lesson, you will be able to build a basic interactive analytics dashboard using Streamlit, allowing users to filter data and visualize results without writing HTML or JavaScript.
What it is
Streamlit is an open-source Python library that turns data scripts into shareable web apps in minutes. It operates on a "top-to-bottom" execution model: every time a user interacts with a widget (like a slider or button), the entire script re-runs from top to bottom. This mental model simplifies state management but requires understanding how to cache expensive operations.
Related terms: st.dataframe() for displaying tables, st.line_chart() for visualizations, and st.session_state for managing variables across reruns.
Why it matters
- Rapid Prototyping: Data scientists can validate hypotheses with stakeholders instantly without waiting for frontend developers.
- Pure Python: No need to learn SQL, HTML, CSS, or JavaScript; if you know Pandas, you can build the app.
- Interactivity: Users can dynamically filter large datasets using sliders, date pickers, and dropdowns.
- Deployment: Apps can be deployed to the cloud with a single command, making sharing effortless.
Syntax or steps
- Install Streamlit via pip:
pip install streamlit. - Create a Python file (e.g.,
app.py) and importstreamlitandpandas. - Load your data (CSV, database, or generated DataFrame).
- Add input widgets (
st.slider,st.selectbox) to capture user preferences. - Filter or transform the data based on those inputs.
- Display results using output functions (
st.write,st.chart). - Run the app locally using
streamlit run app.py.
Example
import streamlit as st
import pandas as pd
import numpy as np
# 1. Generate dummy data
df = pd.DataFrame({
'date': pd.date_range(start='2023-01-01', periods=100),
'sales': np.random.randint(100, 500, size=100)
})
# 2. Sidebar for controls
st.sidebar.title("Filters")
min_sales = st.sidebar.slider("Minimum Sales", int(df['sales'].min()), int(df['sales'].max()))
# 3. Main content
st.title("Sales Analytics Dashboard")
filtered_df = df[df['sales'] >= min_sales]
st.metric(label="Total Records", value=len(filtered_df))
st.line_chart(filtered_df.set_index('date')['sales'])
st.dataframe(filtered_df)
Explanation: The script first creates a DataFrame. A sidebar slider allows the user to set a minimum sales threshold. The main area displays a metric count, a line chart of the filtered data, and the raw table. When the slider moves, the script reruns, filtering the data again before redrawing the charts.
Common mistakes
- Ignoring Caching: Loading large CSVs or running complex queries on every rerun slows down the app. Use
@st.cache_dataabove the loading function. - Modifying Global State: Changing variables outside of
st.session_stateoften leads to unexpected behavior because the script resets. Always use session state for persistent variables. - Heavy Loops in UI Code: Do not put long-running calculations directly in the main flow. Wrap them in cached functions or move them to background tasks if possible.
- Forgetting Imports: Ensure all libraries (Pandas, NumPy, Plotly) are installed in the environment where Streamlit runs.
When to use it
| Feature | Streamlit | Dash (Plotly) |
|---|---|---|
| Learning Curve | Very Low (Pure Python) | Moderate (Callbacks required) |
| Customization | Limited (CSS hacks needed) | High (Full control over layout) |
| Best For | Quick internal tools, MVPs | Production-grade enterprise apps |
Use Streamlit when speed and simplicity are paramount. Choose Dash when you need precise control over layout and interactions for a polished production application.
Practice
Guided Exercise: Add a st.date_input widget to the example above to allow users to select a start date. Filter the DataFrame to show only records after that date.
Challenge: Create a second tab using st.tabs(["Overview", "Details"]). Place the chart in the "Overview" tab and the dataframe in the "Details" tab.
Quick check
Q: Why might your Streamlit app feel slow when you change a slider?
A: Because the entire script reruns from top to bottom. If you are reloading data or performing heavy computations without caching, these operations repeat unnecessarily.
Summary
Streamlit enables rapid development of data applications by abstracting away web technologies, allowing analysts to focus purely on Python logic. Its reactive nature requires careful use of caching to maintain performance, but its simplicity makes it the ideal tool for prototyping and internal analytics dashboards.