Introduction
Altair is a declarative visualization library built on Vega-Lite. Instead of “draw a bar chart,” you describe “I want bars where x=category and y=value, colored by group.” Streamlit renders Altair charts natively with st.altair_chart. This post covers the patterns that matter.
Setup
pip install streamlit altair pandas
Step 1: Basic chart
import streamlit as st
import altair as alt
import pandas as pd
df = pd.read_csv("data.csv")
chart = alt.Chart(df).mark_bar().encode(
x="category:N",
y="value:Q",
color="group:N",
).properties(title="Values by Category", width=600, height=400)
st.altair_chart(chart, use_container_width=True)
Type suffixes: :N (nominal), :O (ordinal), :Q (quantitative), :T (temporal).
Step 2: Line chart with tooltip
chart = alt.Chart(df).mark_line(point=True).encode(
x="date:T",
y="value:Q",
color="series:N",
tooltip=["date:T", "value:Q", "series:N"],
).properties(title="Trend Over Time", width=700, height=400)
st.altair_chart(chart, use_container_width=True)
Hover tooltips are built in — no extra code.
Step 3: Scatter plot with selection
brush = alt.selection_interval()
chart = alt.Chart(df).mark_circle(size=60).encode(
x="x:Q",
y="y:Q",
color=alt.condition(brush, "category:N", alt.value("lightgray")),
).add_params(brush)
st.altair_chart(chart, use_container_width=True)
Drag to select a region — selected points are colored, others grayed out.
Step 4: Layered charts
base = alt.Chart(df).encode(x="date:T")
line = base.mark_line(color="blue").encode(y="value:Q")
points = base.mark_circle(color="red", size=50).encode(y="value:Q")
rule = alt.Chart(pd.DataFrame({"y": [df["value"].mean()]})).mark_rule(color="gray", strokeDash=[5, 5]).encode(y="y:Q")
chart = (line + points + rule).properties(title="Value with Mean Line", width=700, height=400)
st.altair_chart(chart, use_container_width=True)
Layer multiple marks with +.
Step 5: Faceted (small multiples)
chart = alt.Chart(df).mark_bar().encode(
x="category:N",
y="value:Q",
color="group:N",
).facet(
column="region:N",
).properties(title="Values by Region", width=200, height=300)
st.altair_chart(chart, use_container_width=True)
Creates a separate chart per region — great for comparing groups.
Step 6: Interactive filtering
dropdown = alt.binding_select(options=list(df["category"].unique()), name="Category: ")
selection = alt.selection_point(fields=["category"], bind=dropdown)
chart = alt.Chart(df).mark_bar().encode(
x="subcategory:N",
y="value:Q",
color="category:N",
).transform_filter(selection).add_params(selection)
st.altair_chart(chart, use_container_width=True)
A dropdown filter that updates the chart — no Streamlit widgets needed (but you can combine them).
Step 7: Streamlit widgets + Altair
category = st.selectbox("Category", df["category"].unique())
filtered = df[df["category"] == category]
chart = alt.Chart(filtered).mark_bar().encode(
x="subcategory:N",
y="value:Q",
).properties(title=f"Values for {category}")
st.altair_chart(chart, use_container_width=True)
Combine Streamlit widgets with Altair charts for the best of both worlds.
Altair vs Plotly vs Matplotlib
| Altair | Plotly | Matplotlib | |
|---|---|---|---|
| Style | Declarative | Imperative | Imperative |
| Interactivity | Built-in (selections, tooltips) | Built-in (hover, zoom) | Static |
| Learning curve | Medium | Medium | Low |
| Performance | Good (up to ~5k rows) | Good | Fast |
| Customization | Good | Good | Unlimited |
| Best for | Statistical viz, exploration | Dashboards, interactive | Publications, static |
Rule: Altair for statistical exploration and declarative charts. Plotly for dashboards. Matplotlib for publications.
Common mistakes
- Too many rows — Altair struggles with >5k rows. Aggregate first.
- Forgetting type suffixes —
:N,:Q,:Tare important for correct encoding. - Not using
use_container_width=True— charts won’t resize to the container. - Overusing selections — too many interactive elements confuse users.
- Not saving the chart —
chart.save("chart.html")for sharing.
Key Concepts
- Altair = declarative visualization (Vega-Lite)
mark_*= chart type (bar, line, circle, etc.)encode= map data to visual channels (x, y, color, size)selection= interactive filteringfacet= small multiples+= layer charts
What to Try Next
- Replace Plotly with Altair in your dashboard.
- Use Altair for sentiment visualization.
- Combine with caching for large datasets.
- Export charts with
chart.save("chart.html").
FAQ
Altair vs Plotly — which is better for Streamlit?
Altair = cleaner syntax, better for statistical viz, built-in selections. Plotly = more chart types, better for dashboards, more interactive (zoom, pan). Use Altair for exploration; Plotly for dashboards.
Can Altair handle real-time data?
Not well — Altair re-renders the entire chart on each update. For real-time, use Plotly with st.plotly_chart and update the figure object. Or use st.fragment to limit reruns.
Is Altair free?
Yes — open source (BSD license). The rendering happens client-side (Vega-Lite JS), so there’s no server cost. Works offline.<|end|><|start|>write to=assistant<|channel|>analysis<|message|>Created file successfully: src/content/posts/streamlit-altair-charts.md