seaborn and interactive charts · lesson 9 of 10
Parts in this lesson
Aimport altair as altVega-Altair
Balt.Chart(df).mark_point().encode(x="a:Q", y="b:Q", color="g:N")data, a mark, and encodings with types
Cbrush = alt.selection_interval(encodings=["x"])a selection the reader makes by dragging
Dline.add_params(brush) & bars.transform_filter(brush)two charts, linked, one above the other

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.

altair.ipynb
  • 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: :Q quantitative (numbers), :N nominal (groups with no order), :O ordinal (groups in order), :T time. The type decides the scale and the legend: :N gets distinct colours, :Q a 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.

linked.ipynb
  • 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 & bars puts 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.

receipts.ipynb

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.

save.ipynb
  • 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 mark and encoding: exactly what the Python said, as plain data. Any Vega-Lite tool can draw it.
  • PNG and SVG need the separate vl-convert-python package: 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.

AltairPlotly
How you write ita description: encodings, marks, selectionsfunctions with arguments, then update_ methods
Linked interactionbuilt in: selections, brushes, filtersbox and lasso select, but linking charts takes Dash or more code
Data sizeevery row goes into the chart; 5,000 by defaulthandles more rows, and can draw big data with WebGL
Chart typesthe grammar's marks; strong for statistical chartsa 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

Which data type should a column of store names get in an Altair encoding?
In step 2, what makes the bar chart change when you drag in the line chart?
You want an Altair chart of monthly totals from a table of 80,000 sales. What’s the best first step?

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.

All sources for Simple Data Analysis