Declarative charts with Altair
Last updated
Altair describes a chart instead of drawing it: this column on x, that one on y, colour by species, draw points. The description becomes a Vega-Lite chart that a browser draws, and interaction is part of the same description: a brush in one chart can filter another. In this lesson you'll write encodings and marks, link a time series to a bar chart, save a chart, meet Altair's 5,000-row limit, and choose between Altair and Plotly.
By the end of this lesson you can
- Make an Altair chart from encodings, a mark and data types
- Link two charts with a selection, so brushing one filters the other
- Aggregate before charting to stay under Altair’s row limit
- Choose between Altair and Plotly for a job
Encodings and marks
Altair (in full, Vega-Altair) follows the same grammar as 7.7: data, mappings, marks. A chart is a description, and Altair turns it into Vega-Lite, a format for charts written as JSON that a browser draws. Run the cells.
alt.Chart(penguins)is the data,.mark_point()the mark, and.encode(...)the mapping: Altair calls each aesthetic a channel (x,y,color,size,tooltip…).- The first chart's axes start at zero, so the points are squashed into a corner. Altair includes zero in a number axis by default; the second cell turns that off with
scale=alt.Scale(zero=False). (For bars, keep zero, as 6.8 said.) - Each column gets a data type after a colon:
:Qquantitative (numbers),:Nnominal (groups with no order),:Oordinal (groups in order),:Ttime. The type decides the scale and the legend::Ngets distinct colours,:Qa gradient. Altair guesses from pandas' dtypes when you leave it off, but writing it makes the chart say what you mean. tooltip=[...]lists the columns to show on hover, and.interactive()lets the reader pan by dragging and zoom by scrolling.- The third chart shows Altair doing a stat for you:
mean(body_mass_g)in the encoding computes each island's mean in the browser.sort="-x"sorts the bars by their length, longest first. Biscoe's penguins are the heaviest on average, because the Gentoos live there.
Linked charts
In Altair, interaction is part of the description. A selection (Altair calls it a parameter) is something the reader does, like dragging across a chart, and other parts of the chart can depend on it. Run the cell, then drag across some days in the top chart.
alt.selection_interval(encodings=["x"])makes a brush: drag to select a range along the x-axis.encodings=["x"]keeps it to dates; without it, the brush would be a box.line.add_params(brush)puts the brush on the line chart, the daily kilos of all four stores.bars.transform_filter(brush)filters the bar chart's rows to the dates in the brush before adding them up. Drag over a week and the bars show that week's sales by store; drag the brush along to move through time; click outside it to clear it.line & barsputs one chart above the other (|puts them side by side).
This is linked brushing, as in the pair plot of 7.5, written in a few lines. Everything happens in the browser, from the data written into the chart, so it keeps working in a saved file with no Python behind it.
Wrong way: 6,000 rows
Run the cells: a month of receipts, one row per receipt.
MaxRowsError: the number of rows in your dataset (6000) is greater than the maximum allowed (5000). Altair writes every row of the data into the chart's JSON, so the browser can filter and aggregate it. A chart of a million rows would be a file of tens of megabytes, and slow to open. So by default Altair stops at 5,000 rows and tells you.
The chart only needs one number per day, so the fix is to aggregate in pandas first: the third cell sums each day's takings with groupby and charts 30 rows. That's almost always the right fix, and it's what you'd do for any chart anyway.
The error message suggests the other ways, for when you really need every row:
alt.data_transformers.enable("vegafusion")uses the VegaFusion package to do the aggregation in Python before the chart is made. It isn't in this page's Python.alt.data_transformers.disable_max_rows()removes the limit and writes every row into the chart. Fine for 10,000 rows; a bad idea for a million.
Saving, and Altair or Plotly?
Run the cells.
chart.save("penguins.html")writes a web page that loads Vega from the internet and draws the chart, interactions and all.chart.save("penguins.json")writes the Vega-Lite description itself: about 60 KB each, almost all of it the 344 penguins' data.- The second cell opens the JSON and shows its
markandencoding: exactly what the Python said, as plain data. Any Vega-Lite tool can draw it. - PNG and SVG need the separate
vl-convert-pythonpackage:chart.save("penguins.png"). It isn't in this page's Python.
Altair or Plotly? Both make interactive charts from tidy tables, and both save to HTML.
| Altair | Plotly | |
|---|---|---|
| How you write it | a description: encodings, marks, selections | functions with arguments, then update_ methods |
| Linked interaction | built in: selections, brushes, filters | box and lasso select, but linking charts takes Dash or more code |
| Data size | every row goes into the chart; 5,000 by default | handles more rows, and can draw big data with WebGL |
| Chart types | the grammar's marks; strong for statistical charts | a long list, including 3-D, maps and financial charts |
Choose Altair when the interaction is the point, or when you like thinking in the grammar; choose Plotly for big data, unusual chart types, or polished dashboards (it's the base of the Dash framework). For a quick look at data, either; for a printed report, seaborn and matplotlib.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- VanderPlas et al., Altair: Interactive Statistical Visualizations for Python, Journal of Open Source Software 3(32), 2018: what Altair is, and how it builds on Vega-Lite
- Altair: Encodings: channels, and the data types Q, N, O and T
- Altair: Interactive Charts: selections, parameters, and filtering one chart by another
- Altair: Large Datasets: the 5,000-row limit, and the ways around it
- Satyanarayan, Moritz, Wongsuphasawat and Heer, Vega-Lite: A Grammar of Interactive Graphics, IEEE TVCG 23(1), 2017: the grammar Altair writes, interaction included