Streamlit first · Dash as optional supplemental material
Lecture 1 of 2: The next packet introduces Shiny in R.
| Question | Standalone Plotly HTML | Streamlit app |
|---|---|---|
| Where does interaction happen? | Mostly in browser | Browser and Python server |
| Hover, zoom, toggle traces? | Yes | Yes (via embedded Plotly chart) |
| Re-run Python after a widget changes? | No | Yes |
| Query a database or score a model on demand? | Not without another service | Yes, from Python |
| Share as a static file? | Often yes | Requires running app server |
Key idea: A Plotly chart can be interactive without a Python backend. A Streamlit app can recompute its data and charts when inputs change.
Client-side-only: A user hovers over a precomputed sales chart or hides a product series.
Server-backed: A user chooses a region → Python filters millions of records (or queries a database) → computes a new forecast → sends updated results to the browser.
Browser Python server
[Choose a region] --------> [Read selection]
[Filter / query data]
[Compute / fit model]
[Updated chart] <---------- [Return results]| Language | Tools | Typical strengths |
|---|---|---|
| Python | Streamlit | Fast, Python-first analytical apps |
| Python | Dash | Explicit layouts and callback-driven apps |
| Python | Panel, Voilà, Gradio | Notebook/model interfaces and custom apps |
| R | Shiny | Reactive analytical apps with R |
| R | Quarto dashboards + Shiny | Reporting with optional server interactivity |
localhost.st.title(), st.slider(), and st.plotly_chart().Mental model: write a Python script that describes the page.
From a terminal in your project directory:
Create a file called app.py. Run:
http://localhost:8501).app.py; Streamlit can rerun the app.Save this as app.py:
import streamlit as st
import pandas as pd
st.title("My first data app")
st.write("Explore a tiny dataset with Python.")
data = pd.DataFrame({"month": ["Jan", "Feb", "Mar"],
"sales": [120, 150, 135]})
st.dataframe(data)st.title() creates a heading.st.write() displays text or many Python objects.st.dataframe() provides a scrollable, interactive table.import streamlit as st
st.title("Interactive input")
minimum_sales = st.slider("Minimum sales", 0, 200, 100)
st.write("Selected threshold:", minimum_sales)st.slider() returns the user’s chosen value.import pandas as pd
import plotly.express as px
import streamlit as st
sales = pd.DataFrame({
"month": ["Jan", "Feb", "Mar", "Apr"],
"sales": [120, 150, 135, 180],
})
threshold = st.slider("Minimum sales", 0, 200, 100)
filtered = sales[sales["sales"] >= threshold]
fig = px.bar(filtered, x="month", y="sales", title="Monthly sales")
st.plotly_chart(fig, use_container_width=True)Notice: Python filters the data; Plotly handles chart interactions in the browser.
import pandas as pd
import plotly.express as px
import streamlit as st
st.title("Sales explorer")
df = pd.DataFrame({"region": ["East", "East", "West", "West"],
"month": ["Jan", "Feb", "Jan", "Feb"],
"sales": [120, 160, 90, 140]})
region = st.selectbox("Region", sorted(df["region"].unique()))
view = df[df["region"] == region]
st.metric("Total sales", f"${view['sales'].sum():,.0f}")
st.plotly_chart(px.bar(view, x="month", y="sales"),
use_container_width=True)
st.dataframe(view)import streamlit as st
st.set_page_config(page_title="Explorer", layout="wide")
st.title("Explorer")
with st.sidebar:
year = st.selectbox("Year", [2024, 2025, 2026])
left, right = st.columns(2)
with left:
st.metric("Selected year", year)
with right:
st.info("Place a chart or table here.")st.set_page_config() belongs near the beginning of the script.import pandas as pd
import streamlit as st
uploaded = st.file_uploader("Choose a CSV", type="csv")
if uploaded is not None:
df = pd.read_csv(uploaded)
st.write("Rows:", len(df))
st.dataframe(df.head())
else:
st.info("Upload a CSV to begin.")import pandas as pd
import streamlit as st
@st.cache_data
def load_data(path):
return pd.read_csv(path)
df = load_data("sales.csv")
st.dataframe(df.head())st.cache_data is for reusable data results; cache entries can be shared across sessions.st.cache_resource for reusable resources such as model objects or connections.import streamlit as st
if "clicks" not in st.session_state:
st.session_state.clicks = 0
if st.button("Count a click"):
st.session_state.clicks += 1
st.write("Clicks in this session:", st.session_state.clicks)st.session_state retains values for a user session across reruns.app.py and a dependency file (such as requirements.txt) together.Install: python -m pip install dash plotly
from dash import Dash, dcc, html, Input, Output
import plotly.express as px
app = Dash(__name__)
app.layout = html.Div([
dcc.Slider(1, 5, 1, id="minimum"),
dcc.Graph(id="chart"),
])
@app.callback(Output("chart", "figure"), Input("minimum", "value"))
def update_chart(minimum):
df = px.data.iris()
return px.scatter(df[df.sepal_length >= minimum],
x="sepal_width", y="sepal_length",
color="species")
if __name__ == "__main__":
app.run(debug=True)Run: python app.py. The callback connects slider changes to the figure.
Next lecture: Shiny applies the same client/server ideas using R and a reactive programming model.