Facet Charts in Altair: Small Multiples With facet, row, and column

Split an Altair chart into small multiples with facet(), row, and column, then control wrapping, axis scales, layers, order, and headers.

To split an Altair chart into one panel per category, call .facet("column_name:N", columns=3) on it, or put row and column inside encode() for a grid. Every panel shares the same axes and colors unless you say otherwise. This post targets Altair 6.2.

Quick Example

Six plant species, one panel each, wrapped three to a row.

import altair as alt
import numpy as np
import pandas as pd

# Sample data: weekly seedling heights for six species under two kinds of light.
rng = np.random.default_rng(24)
final_height = {"Basil": 24, "Lettuce": 14, "Marigold": 22,
                "Pepper": 31, "Sunflower": 96, "Tomato": 58}
weeks = np.arange(1, 11)

rows = []
for species, top in final_height.items():
    midpoint = rng.uniform(4.5, 6.0)
    for light, factor in [("Windowsill", 0.7), ("Grow light", 1.0)]:
        height = top * factor / (1 + np.exp(-(weeks - midpoint) / 1.3))
        height *= rng.normal(1, 0.05, len(weeks))
        rows.append(pd.DataFrame({"species": species, "light": light,
                                  "week": weeks, "height_cm": height.round(1)}))
plants = pd.concat(rows, ignore_index=True)

base = alt.Chart(plants, width=150, height=130).mark_line(point=True).encode(
    x=alt.X("week:Q", title="Week"),
    y=alt.Y("height_cm:Q", title="Height (cm)"),
    color=alt.Color("light:N", title="Light", legend=alt.Legend(orient="top")),
)

wrapped = base.facet(alt.Facet("species:N", title=None), columns=3)
wrapped

Six Altair line charts of seedling height over ten weeks, one per species, with grow light above windowsill in every panel

width and height apply to each panel, not the whole figure. With three 150-pixel panels plus axes, the chart comes out a little over 500 pixels wide. title=None drops the "species" heading above the panels, since the panel names already say what they are.

Make a Grid With row and column

Use the row and column channels when you have two variables to split by. Each combination gets a panel.

subset = plants[plants["species"].isin(["Basil", "Pepper", "Tomato"])]

grid = alt.Chart(subset, width=150, height=120).mark_bar(color="#588157").encode(
    x=alt.X("week:O", title="Week", axis=alt.Axis(labelAngle=0, values=[2, 4, 6, 8, 10])),
    y=alt.Y("height_cm:Q", title="Height (cm)"),
    column=alt.Column("species:N", title=None),
    row=alt.Row("light:N", title=None),
)
grid

Two by three grid of Altair bar charts, with light type as rows and basil, pepper, and tomato as columns, on a shared height axis

Use either row alone or column alone for a single strip of panels. The columns wrapping argument only works with facet(), not with row and column.

Give Each Panel Its Own Y Axis

A shared axis lets you compare sizes, but sunflowers reach about 100 cm and flatten everything else. resolve_scale(y="independent") scales each panel to its own data.

independent = wrapped.resolve_scale(y="independent")
independent

The six species panels with separate y axes, so the shape of each growth curve is visible, from lettuce topping out near 14 cm to sunflower near 100 cm

Now the growth curves can be compared by shape, but not by height. Say so in a title or caption, because readers tend to assume panels share a scale. x="independent" does the same for the x axis.

Facet a Layered Chart

You can't add a row or column encoding to just one layer. Build the layers from the same data, then call .facet() on the combined chart.

line = alt.Chart().mark_line(color="#bc4749").encode(
    x=alt.X("week:Q", title="Week"),
    y=alt.Y("height_cm:Q", title="Height (cm)"),
    detail="light:N",
    strokeDash=alt.StrokeDash("light:N", title="Light",
                              legend=alt.Legend(orient="top")),
)
mean_rule = alt.Chart().mark_rule(color="gray").encode(y="mean(height_cm):Q")
mean_text = alt.Chart().mark_text(align="left", baseline="bottom", color="gray").encode(
    x=alt.value(4), y="mean(height_cm):Q",
    text=alt.Text("mean(height_cm):Q", format=".1f"),
)

layered = alt.layer(
    line, mean_rule, mean_text, data=plants
).properties(width=150, height=130).facet(
    alt.Facet("species:N", title=None), columns=3
).resolve_scale(y="independent")
layered

Faceted Altair chart where each species panel has two growth lines and a gray horizontal line labeled with that species' mean height

The data goes in alt.layer(..., data=plants) and the individual charts are created empty with alt.Chart(). If the layers are built from different DataFrames and no data is set at the top level, Altair raises ValueError: Facet charts require data to be specified at the top level. The mean is computed inside each panel automatically.

Sort the Panels and Style the Headers

Panels are in alphabetical order by default. Pass sort a list, or an aggregate to order panels by a value. Headers are styled with alt.Header.

styled = base.facet(
    alt.Facet(
        "species:N",
        title=None,
        sort=alt.EncodingSortField(field="height_cm", op="max", order="descending"),
        header=alt.Header(labelFontSize=14, labelFontWeight="bold",
                          labelAnchor="start", labelColor="#344e41"),
    ),
    columns=3,
    spacing=24,
).configure_view(fill="#f4f1ea", stroke=None)
styled

Species panels ordered from tallest to shortest, starting with sunflower, with bold left-aligned headers and a cream panel background

configure_* methods apply to the whole chart, so call them last, after facet(). To reuse a look like this across charts, make it an Altair theme.

facet, row and column, or repeat?

You want Use
One panel per category, wrapped into rows .facet("col:N", columns=3)
A grid from two categories row= and column= encodings
The same chart for several different columns .repeat([...])
Different chart types side by side \| and & concatenation

Faceting splits rows of data by a category. Repeating keeps all the rows and swaps which column is plotted. Repeated panels get their own axis scales, so check the tick labels before comparing them:

measurements = plants.pivot(index=["species", "week"], columns="light",
                            values="height_cm").reset_index()

repeated = alt.Chart(measurements, width=230, height=200).mark_circle(size=50).encode(
    x=alt.X("week:Q", title="Week"),
    y=alt.Y(alt.repeat("column"), type="quantitative"),
    color=alt.Color("species:N", title="Species"),
).repeat(column=["Windowsill", "Grow light"])
repeated

Two Altair scatter plots of height by week side by side, one for the windowsill column and one for the grow light column, colored by species

Practical Tips

  • width="container" doesn't work on faceted charts. Set a fixed panel width that fits your page.
  • Six to twelve panels is a comfortable range. Past that, filter to the interesting ones or switch to a heatmap.
  • Put the legend on top to leave the full width for panels.
  • Seaborn users: .facet() is the counterpart of FacetGrid, relplot, and catplot (see titles on Seaborn facet grids). In Plotly Express the arguments are facet_col and facet_row.

Similar Topics