Altair scatter plot: encode categories, add tooltips, and save to HTML
Altair is a Python library for declaring how data fields map to visual properties. Build a point chart with `Chart(...).mark_point().encode(...)`; mark measurements as quantitative (`Q`) and groups as nominal (`N`) so the axes and colors match their meaning. This guide uses a fictional campaign table to add categorical colors, tooltips, pan and zoom, then save the chart as HTML. The official Vega-Altair 6 documentation was checked on 2026-11-18.
Altair scatter plot: encode categories, add tooltips, and save to HTML
Altair is a Python library for declaring how data fields map to visual properties. Build a point chart with Chart(...).mark_point().encode(...); mark measurements as quantitative (Q) and groups as nominal (N) so the axes and colors match their meaning. This guide uses a fictional campaign table to add categorical colors, tooltips, pan and zoom, then save the chart as HTML. The official Vega-Altair 6 documentation was checked on 2026-11-18.
How does Altair’s declarative grammar work?
Altair is a declarative visualization library for Python built on Vega and Vega-Lite. Instead of issuing drawing commands one by one, you declare which data columns map to the x-axis, y-axis, color or tooltip. alt.Chart(data) associates the data with a chart, mark_point() chooses dots, and encode() defines the relationship between fields and visual channels. Altair expresses this configuration as a Vega-Lite specification for rendering, so when a color or axis looks unexpected, you can first check the data values and encoding types.
For example, map a text field called channel to categorical color to create one color and legend entry per channel. Ad spend and sales, by contrast, are continuous quantities that position each point. Declaring this distinction in code makes your intent clear, including for numeric codes that Python’s data type alone cannot identify as categories.
Install and build a scatter plot
The basic example needs Python, pandas and Altair. Install them in your Python environment:
python -m pip install altair pandasThe six rows below are made-up campaign data to demonstrate the workflow; they are not actual advertising results. Save the code as altair_scatter.py and run it to create altair_scatter.html in the current folder.
import altair as alt
import pandas as pd
df = pd.DataFrame({
"campaign": ["A-01", "A-02", "B-01", "B-02", "C-01", "C-02"],
"ad_spend": [2, 4, 3, 6, 5, 8],
"sales": [18, 25, 20, 31, 26, 38],
"channel": ["Search", "Search", "Social", "Social", "Email", "Email"],
"region": ["North", "South", "North", "South", "North", "South"]
})
chart = (
alt.Chart(df)
.mark_point(filled=True, size=100)
.encode(
x=alt.X("ad_spend:Q", title="Ad spend (example units)"),
y=alt.Y("sales:Q", title="Sales (example units)"),
color=alt.Color("channel:N", title="Campaign channel"),
tooltip=[
alt.Tooltip("campaign:N", title="Campaign"),
alt.Tooltip("ad_spend:Q", title="Ad spend"),
alt.Tooltip("sales:Q", title="Sales"),
alt.Tooltip("region:N", title="Region")
]
)
.properties(
title="Example campaigns by channel: ad spend and sales",
width=500,
height=320
)
.interactive()
)
chart.save("altair_scatter.html")By default, HTML export loads the Vega, Vega-Lite and vegaEmbed JavaScript libraries from an online CDN. The file stays small, but opening it requires internet access. For an offline file, install the optional export dependencies and use chart.save("altair_scatter.html", inline=True). The official installation guide lists altair[save] for offline HTML export. The chart may appear blank if JavaScript is disabled or the CDN cannot be reached.
The code was reviewed against the official API documentation but was not run in a Python environment or browser. The behavior described below is expected from the docs, not a runtime test result.
How data types map to visual channels
Altair encodings connect data meaning to visual properties. Its documentation defines Q as a continuous quantity, N as an unordered category, O as an ordered category, and T as a date or time. Altair can infer types from a pandas DataFrame, but inference cannot decide whether a numeric code represents a category or a measurement. Specify the intended type in the encoding when it matters.
| Setting | Example | Visual role | What to check |
|---|---|---|---|
x, y | ad_spend:Q, sales:Q | Horizontal and vertical position of each campaign | Are both values numeric and aligned to the same campaign row? |
color | channel:N | Distinguishes Search, Social and Email with colors and a legend | Are values categories, with no spelling variants splitting groups? |
tooltip | Campaign, ad spend, sales and region | Shows details when a pointer is over a point | Does it include only useful fields and exclude sensitive data? |
If a numeric channel_id actually stands for a channel category, do not treat it as a measured quantity; declare it as nominal, for example channel_id:N. Q and N are semantic measurement types, not just aliases for Python numbers and strings. They affect whether Altair uses a continuous color scale or discrete category colors and a legend.
Check the result in HTML
Open altair_scatter.html in a modern browser with JavaScript enabled. Confirm that six points and three channel categories appear. Hover over each point and check that campaign, ad spend, sales and region match the same source row. Drag or scroll to pan and zoom, then make sure the relationship between points and axes remains clear. If the result differs from expectations, diagnose it in this order:
**`ModuleNotFoundError`:** run `python -m pip install altair pandas` in the same Python environment used to run the script. If you have multiple virtual environments, use the same interpreter for installation and execution.
**The color legend is a continuous scale:** if the field is a category, declare it as `channel:N` and determine whether numeric values are measurements or category identifiers.
**There are more categories than expected:** check spaces, capitalization and spelling in `channel`. For example, `Social` and `social` are different string values.
**The HTML opens as a blank page:** check internet access and CDN reachability. For offline use, install `altair[save]` and save with `inline=True`.
**`MaxRowsError` appears:** when a DataFrame is embedded directly, the default transformer rejects datasets with more than 5,000 rows. Filter or summarize first, or choose a documented data transformer or external-data approach for larger datasets. Disabling the limit and embedding a large table can make the HTML and notebook slow and large.
The ad spend and sales values are fictional and show neither causation nor actual campaign performance. With real data, check that currency, time period and aggregation units match, and compare category meanings and missing values against the source data.
Sources
[Vega-Altair documentation: Overview](https://altair-viz.github.io/getting_started/overview.html)
[Vega-Altair documentation: Installation](https://altair-viz.github.io/getting_started/installation)
[Vega-Altair documentation: Encodings and data types](https://altair-viz.github.io/user_guide/encodings/index.html)
[Vega-Altair documentation: Specifying data](https://altair-viz.github.io/user_guide/data.html)
[Vega-Altair documentation: Interactive charts](https://altair-viz.github.io/user_guide/interactions/index.html)
[Vega-Altair tutorial: Pan and zoom](https://altair-viz.github.io/altair-tutorial/notebooks/01-Cars-Demo.html)
[Vega-Altair documentation: Saving charts and offline HTML](https://altair-viz.github.io/user_guide/saving_charts.html)
[Vega-Altair documentation: Large datasets](https://altair-viz.github.io/user_guide/large_datasets.html)