Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 31 ยท Altair and Vega-Lite

Layering, Faceting and Concatenation

Combine Altair charts with layer, hconcat, vconcat, facet and repeat. Learn how scales and axes are shared or independent and how small multiples work.

One chart rarely tells a whole story. You want a line with its data points on top, a reference line across a bar chart, four panels that show the same measure for four regions, or a scatter next to a histogram. Vega-Lite and Altair handle all of this with a small set of composition operators. Learn the four ideas and you can build most dashboards-in-a-picture without leaving the grammar.

The four ideas are: layer (draw charts on top of each other in one set of axes), concat (put charts side by side or stacked), facet (split one chart into panels by a field) and repeat (repeat one chart for several fields). The tricky part is not the syntax but a single question: do the pieces share scales?

Altair cannot run on this site, so the chart code is read-only. The runnable examples are stand-ins in JavaScript: a tiny small-multiples drawing and a calculation of shared and independent scale domains. They show the mechanism, not the real library.

Layer: charts on the same axes

A layered chart draws several marks over the same data space. In Altair you use alt.layer(a, b) or the + operator.

Python
import altair as alt

base = alt.Chart(prices).encode(x="date:T", y="close:Q")

line = base.mark_line()
points = base.mark_point(size=30)
average = alt.Chart(prices).mark_rule(color="tomato").encode(y="mean(close):Q")

chart = line + points + average

The layers share one x scale and one y scale by default, so the rule at the mean lines up with the line chart. This is the right tool for labels on bars (a mark_text layer over a mark_bar layer), for error bands under a line (mark_area plus mark_line) and for annotations.

When every layer uses the same data, put the data in the shared parent: alt.layer(line, points, data=prices) or use a base chart as above. Layers can also bring their own data when the annotation is a small table of its own.

Concatenation: side by side and stacked

alt.hconcat(a, b) or a | b puts charts in a row. alt.vconcat(a, b) or a & b stacks them in a column. alt.concat(*charts, columns=3) wraps them into a grid.

Python
scatter = alt.Chart(cars).mark_point().encode(x="weight:Q", y="mpg:Q")
hist = alt.Chart(cars).mark_bar().encode(x=alt.X("mpg:Q", bin=True), y="count()")

dashboard = scatter | hist

The pieces of a concatenation can be completely different charts with different data. By default, each piece has its own scales, because there is no reason a weight axis and a count axis should agree. Shared interaction is a separate matter, covered in the next lesson.

Facet: small multiples from one field

A facet repeats one chart specification once for each value of a field. This pattern is known as small multiples, and it is one of the most effective ways to compare groups without piling lines on top of each other.

Python
chart = (
    alt.Chart(sales)
    .mark_line()
    .encode(x="month:O", y="units:Q")
    .properties(width=160, height=100)
    .facet("region:N", columns=2)
)

Alternatively, assign the column or row channel inside the encoding: .encode(column="region:N"). Use the .facet(...) method when you need columns= to wrap panels or when you want the facet applied to a layered chart as a whole.

By default, all panels share the same scales, so a bar that is twice as tall really means twice the value in every panel. That is the honest default for comparison.

Repeat: one chart, several fields

Faceting splits by a value. Repeat runs the same chart for several fields, which is how you draw a scatter-plot matrix or one histogram per numeric column.

Python
numeric = ["mpg", "weight", "horsepower"]

chart = (
    alt.Chart(cars)
    .mark_bar()
    .encode(x=alt.X(alt.repeat("column"), type="quantitative", bin=True), y="count()")
    .repeat(column=numeric)
)

alt.repeat("column") is a placeholder filled in with each name in the list. You can repeat across both row and column to get every pairing, which gives a scatter matrix.

flowchart TB
    subgraph LAYER["layer: one coordinate system"]
      L1["line"] --- L2["points"] --- L3["rule"]
    end
    subgraph CONCAT["concat: separate charts"]
      C1["chart A"] --- C2["chart B"]
    end
    subgraph FACET["facet: one spec x values"]
      F1["region N"] --- F2["region S"] --- F3["region E"]
    end
    subgraph REPEAT["repeat: one spec x fields"]
      R1["field 1"] --- R2["field 2"] --- R3["field 3"]
    end

Layer overlays; concat places different charts; facet splits by a field's values; repeat varies which field is drawn.

Resolving scales, axes and legends

Whether pieces share a scale is controlled by resolve. There are three resolve methods: resolve_scale, resolve_axis and resolve_legend, each taking a channel and either "shared" or "independent".

Python
# Two layers with different units: give the second its own y scale
(line_a + line_b).resolve_scale(y="independent")

# Facets where each panel zooms to its own data
base.facet("region:N").resolve_scale(y="independent")

# Keep scales shared but draw an axis on every panel
base.facet("region:N").resolve_axis(y="independent")

Typical defaults to remember:

Operator Scales by default Notes
layer shared Overlays must agree, or you resolve them independently.
facet and repeat shared Honest comparison; independent scales hide differences in size.
hconcat / vconcat / concat independent Each view is its own chart.

When you make a scale independent, the axis labels become the only way to know the magnitude, so the panels can look equally tall while meaning very different values. Use it deliberately: it helps when you care about the shape of each series, not the size. A dual-axis layer (independent y with two different units) is a classic way to mislead; see the pitfalls lesson.

Sizing and headers

A faceted or concatenated chart is made of many small views, so width and height apply per panel, not to the whole figure. Put .properties(width=..., height=...) on the chart before faceting it, and put title on the outer chart. Facet headers show the field value; customize them with header=alt.Header(title=None) inside the alt.Facet/alt.Row/alt.Column definitions. Setting columns= wraps panels into a grid when you have many categories.

A small-multiples stand-in

The page below groups a list of records by region and draws one little bar chart per region. A checkbox switches between shared and independent y scales, which is what resolve_scale(y=...) does in Altair. Try both and compare how a small region looks when it shares the big region's scale.

Small multiples with shared or independent scales

With shared scales, the South panel looks small, which is the truth: it sells far less. With independent scales every panel fills its frame and you see the shape of each series, but you can no longer compare sizes by eye. Altair's facet(...) with resolve_scale(y="independent") is the same trade-off.

Computing shared and independent domains

Under the surface, "shared" means one domain computed from all the data and "independent" means one domain per group. The console stand-in below prints both so you can see exactly which numbers each choice would give the axis.

JS Shared versus independent domains

Press Run (or Ctrl + Enter) to see the console output here.

No output.

(These are the raw data extents. For bars, Vega-Lite would extend each domain down to zero, as the SVG panels above do.) The last two lines show why layers with very different units are a problem on a shared scale: the small series gets squashed against the bottom. Independent scales fix the squashing but introduce the dual-axis risk, so most of the time two stacked charts (vconcat) with a shared x axis communicate better.

Choosing an operator

  • Same data space, extra marks: layer.
  • Different charts, each complete: concat.
  • Same chart for each category: facet.
  • Same chart for each column or pair of columns: repeat.

A layered chart can itself be faceted, and facets can sit inside concatenations, but nesting has limits (for example, facets cannot be layered on top of other charts). When the spec gets hard to reason about, step back and ask whether two simpler charts would say it better.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You want a line chart with a horizontal rule at the average. Which operator fits best?

    Layer overlays several marks on one set of axes, so the rule and the line use the same scale.
  2. 2. By default, how are scales treated in a facet?

    Facets share scales by default so panels can be compared fairly. Use resolve_scale to make them independent.
  3. 3. What does repeat vary, compared with facet?

    Facet makes one panel per value (for example each region). Repeat reruns the chart for each field in a list, such as three numeric columns.
  4. 4. Why is an independent y scale on facet panels risky?

    Each panel zooms to its own range, so heights stop being comparable. Reader must read the axis numbers to know the size.
  5. 5. Where do width and height apply in a faceted chart?

    Size properties set on the base chart describe a single panel; the full figure grows with the number of panels.

Summary

  • Four operators compose charts: layer (+), concat (|, &), facet and repeat.
  • Layers, facets and repeats share scales by default; concatenated charts scale independently.
  • resolve_scale, resolve_axis and resolve_legend switch a channel between shared and independent.
  • Shared scales make panels honestly comparable; independent scales show shape but hide size, so use them on purpose.
  • Width and height describe one panel, so set them before faceting.
  • The JavaScript examples are stand-ins that show the mechanics of small multiples and domains.

Next: Selections and Interactive Altair Charts