The Analogy: A Photo Lab's Contact Sheet
At the end of a shooting day a roll of thirty-six exposures comes into the film lab. Rather than make a full print of every frame, the technician lays the developed negatives directly on a sheet of photographic paper and exposes the whole strip at once, so each frame prints at its own small size in neat rows across a single sheet. This is the contact sheet, and its purpose is not to make any one frame beautiful but to let the photographer see the entire roll together and decide which frames are worth enlarging.
The discipline that makes the sheet useful is a single shared setting. Every frame is printed at the same enlarger height, the same exposure time, the same paper grade, so a thin under-exposed negative prints pale and a dense over-exposed one prints dark. Because the conditions are identical across the sheet, the photographer can hold the sheet up, compare frame twelve against frame thirty directly, and trust that a difference on the paper is a real difference on the film rather than an artefact of how each was printed.
The layout itself carries meaning. Frames sit in the order they were shot, and the technician can arrange the sheet so that all the portraits fall in one block and all the landscapes in another, or split a wedding job so the ceremony frames sit above the reception frames. Nothing is added or removed -- the same negatives are simply organised into panels -- and the grid lets the eye sweep a row and drop down a column to find the frame it wants.
The temptation, and the failure, is to make each frame look its best. If the technician re-exposes every frame on its own -- pushing a thin negative brighter, pulling a dense one darker, cropping each to fill its cell -- the sheet turns into a set of flattering little portraits that can no longer be compared. A hopelessly under-exposed frame now looks as strong as a perfectly lit one, because each was fitted to its own cell rather than to a shared scale. The sheet still shows all thirty-six frames, but its one job -- letting you judge them side by side -- is destroyed. That is precisely what a faceted plot does when you give it free scales.
Syntax or Core Structure
Faceting takes a single plot specification and repeats it across a grid of panels, one panel per level of a grouping variable, with every panel drawn on the same scales by default. The plot's layers, mappings and geoms are unchanged; faceting only decides how the rows of the data are split across panels. The simplest form is facet_wrap(~ var), which lays one panel per level of var and wraps them into a rectangular block.
library(ggplot2)
sales <- data.frame(
region = c("N", "N", "N", "S", "S", "S", "S"),
product = c("A", "A", "B", "A", "B", "B", "B"),
value = c(12, 18, 30, 40, 50, 60, 70),
stringsAsFactors = FALSE
)
p <- ggplot(sales, aes(x = product, y = value)) +
geom_point() +
facet_wrap(~ region)
built <- ggplot_build(p)
tab <- as.integer(table(built$data[[1]]$PANEL))
writeLines(sprintf("%-16s: %d", "layers", length(built$data)))
writeLines(sprintf("%-16s: %d", "total rows", nrow(sales)))
writeLines(sprintf("%-16s: %d", "panels", nrow(built$layout$layout)))
writeLines(sprintf("%-16s: %s", "panel var",
paste(sort(unique(sales$region)), collapse = " ")))
writeLines(sprintf("%-16s: %s", "rows per panel", paste(tab, collapse = " ")))
writeLines(sprintf("%-16s: %s", "rows reconcile",
if (sum(tab) == nrow(sales)) "TRUE" else "FALSE"))
Output:
layers : 1
total rows : 7
panels : 2
panel var : N S
rows per panel : 3 4
rows reconcile : TRUE
Faceting adds no layers -- length(built$data) is still 1, because there is one geom_point -- but the single layer's rows are now stamped with a PANEL column that says which panel each row is drawn in. There are two regions, so two panels, laid out alphabetically as N then S. Tallying the PANEL column shows three rows in the N panel and four in the S panel, and those counts sum back to the seven rows of the frame: faceting partitions the data, it never duplicates or drops it. The whole plot still shares one x scale and one y scale, so a point at height 50 means the same thing in both panels.
Technical Depth: Wrap, Grid, Empty Panels and Free Scales
Two faceting functions, two jobs
R has two faceting functions and they answer different questions. facet_wrap takes one or more variables, makes a panel for each combination that actually occurs in the data, and flows those panels into a block whose shape you steer with nrow or ncol. facet_grid takes a rows ~ cols formula and builds a true two-dimensional matrix: every level of the row variable crossed with every level of the column variable, whether or not that combination appears in the data. The table below sorts out which to reach for.
| Function | Panel rule | Layout you control | Empty combinations | Best for |
|---|---|---|---|---|
| facet_wrap(~ a) | one per observed level | nrow, ncol | omitted | many levels of one variable |
| facet_wrap(~ a + b) | one per observed a,b pair | nrow, ncol | omitted | sparse crossings |
| facet_grid(a ~ b) | every a-by-b cell | fixed by the formula | drawn empty | comparing across a full matrix |
| facet_grid(a ~ .) | one row per level of a | rows only | drawn empty | a stack of panels sharing an x axis |
The rule of thumb: use facet_wrap when you have one variable with many levels and only want the panels that exist, and use facet_grid when the grid itself is the message and an empty cell is worth showing as a gap.
Adding a second faceting variable
facet_grid(region ~ product) crosses the two variables into a matrix of panels, one per cell, filled row by row.
p <- ggplot(sales, aes(x = value, y = value)) +
geom_point() +
facet_grid(region ~ product)
built <- ggplot_build(p)
lay <- built$layout$layout
cells <- sprintf("%s.%s", lay$region, lay$product)
counts <- as.integer(table(factor(built$data[[1]]$PANEL,
levels = seq_len(nrow(lay)))))
writeLines(sprintf("%-16s: %d", "grid rows", length(unique(lay$region))))
writeLines(sprintf("%-16s: %d", "grid cols", length(unique(lay$product))))
writeLines(sprintf("%-16s: %d", "panels", nrow(lay)))
writeLines(sprintf("%-16s: %s", "cells", paste(cells, collapse = " ")))
writeLines(sprintf("%-16s: %s", "cell counts", paste(counts, collapse = " ")))
writeLines(sprintf("%-16s: %s", "counts reconcile",
if (sum(counts) == nrow(sales)) "TRUE" else "FALSE"))
Output:
grid rows : 2
grid cols : 2
panels : 4
cells : N.A N.B S.A S.B
cell counts : 2 1 1 3
counts reconcile: TRUE
Two regions crossed with two products give four panels, laid out row by row as N.A, N.B, S.A, S.B. The cell counts 2, 1, 1, 3 record how many rows fall in each, and they sum to seven, the whole frame. Every possible cell is present here because the data happens to fill all four.
The empty-panel difference
The moment a combination is missing, facet_wrap and facet_grid part ways. Drop the single S-with-A row from the frame and ask each function how many panels it draws.
sparse <- sales[!(sales$region == "S" & sales$product == "A"), ]
combos_possible <- length(unique(sparse$region)) * length(unique(sparse$product))
present <- unique(sprintf("%s.%s", sparse$region, sparse$product))
wrap_panels <- length(present)
grid_panels <- combos_possible
all_cells <- as.vector(outer(sort(unique(sparse$region)),
sort(unique(sparse$product)),
paste, sep = "."))
missing <- setdiff(all_cells, present)
writeLines(sprintf("%-16s: %d", "combos possible", combos_possible))
writeLines(sprintf("%-16s: %d", "combos present", length(present)))
writeLines(sprintf("%-16s: %d", "grid panels", grid_panels))
writeLines(sprintf("%-16s: %d", "wrap panels", wrap_panels))
writeLines(sprintf("%-16s: %d", "empty in grid", grid_panels - wrap_panels))
writeLines(sprintf("%-16s: %s", "missing cell", missing[1]))
Output:
combos possible : 4
combos present : 3
grid panels : 4
wrap panels : 3
empty in grid : 1
missing cell : S.A
facet_grid still draws four panels because the S row and the A column both still exist, so the S-by-A cell is reserved and rendered empty -- a visible gap that says "this combination was not observed". facet_wrap draws only the three panels that have data. Neither is wrong; they answer different questions. If the absence of S-with-A is itself informative, the grid's empty panel shows it. If you only care about the combinations that occurred, the wrap keeps the plot compact.
Free scales, and why the default is shared
By default every panel shares one x scale and one y scale, which is what makes panels comparable. Passing scales = "free_y" (or "free_x", or "free") lets each panel range its own axis to its own data. That is occasionally what you want and often a trap, so it is worth seeing exactly what it changes.
shared <- range(sales$value)
by_region <- tapply(sales$value, sales$region, range)
writeLines(sprintf("%-16s: %d", "layers", 1))
writeLines(sprintf("%-16s: %d", "panels", length(by_region)))
writeLines(sprintf("%-16s: %d %d", "shared y range", shared[1], shared[2]))
writeLines(sprintf("%-16s: %d %d", "free y N", by_region[["N"]][1], by_region[["N"]][2]))
writeLines(sprintf("%-16s: %d %d", "free y S", by_region[["S"]][1], by_region[["S"]][2]))
writeLines(sprintf("%-16s: %d", "shared span", shared[2] - shared[1]))
writeLines(sprintf("%-16s: %d", "free span N",
by_region[["N"]][2] - by_region[["N"]][1]))
writeLines(sprintf("%-16s: %d", "free span S",
by_region[["S"]][2] - by_region[["S"]][1]))
Output:
layers : 1
panels : 2
shared y range : 12 70
free y N : 12 30
free y S : 40 70
shared span : 58
free span N : 18
free span S : 30
Under shared scales both panels span 12 to 70, so the N panel's points sit low and the S panel's points sit high -- the plot tells you at a glance that S is the bigger region. Under free scales the N panel would range only 12 to 30 and the S panel only 40 to 70, each stretched to fill its own panel height. The two panels would then look similarly full even though N's span of 18 and S's span of 30 are different, and both are far short of the shared 58. Reading the two free-scaled panels as if they were comparable is exactly the contact-sheet mistake: each frame fitted to its own cell, no longer judged against the others.
Real World Example: A Three-Station Monitoring Dashboard
An environmental team runs three noise-monitoring stations and wants one faceted panel per station, each showing that station's six readings for the day. The dashboard is meant to answer one question at a glance: which station is loud, which is quiet, and which is swinging. The summary below is computed in base R and printed by hand; the plot is faceted by station, and the reported figures are the structural facts the grammar guarantees.
library(ggplot2)
readings <- data.frame(
station = rep(c("ALPHA", "BETA", "GAMMA"), each = 6),
hour = rep(1:6, 3),
v = c(48, 50, 52, 49, 51, 50,
10, 20, 30, 40, 50, 60,
1, 2, 3, 2, 1, 3),
stringsAsFactors = FALSE
)
agg <- aggregate(v ~ station, readings,
function(x) c(n = length(x), mean = mean(x),
min = min(x), max = max(x)))
stats <- data.frame(station = agg$station, agg$v)
p <- ggplot(readings, aes(x = hour, y = v)) +
geom_line() +
facet_wrap(~ station, scales = "free_y")
built <- ggplot_build(p)
rows <- as.integer(table(built$data[[1]]$PANEL))
writeLines(sprintf("%-8s%4s%6s%6s%6s", "STATION", "N", "MEAN", "MIN", "MAX"))
writeLines(strrep("-", 30))
for (i in seq_len(nrow(stats))) {
writeLines(sprintf("%-8s%4d%6d%6d%6d", stats$station[i], stats$n[i],
stats$mean[i], stats$min[i], stats$max[i]))
}
writeLines(strrep("-", 30))
writeLines(sprintf("%-8s%4d", "TOTAL", nrow(readings)))
writeLines("")
writeLines(sprintf("%-18s: %d", "layers", length(built$data)))
writeLines(sprintf("%-18s: %d", "panels", nrow(built$layout$layout)))
writeLines(sprintf("%-18s: %d", "readings", nrow(readings)))
writeLines(sprintf("%-18s: %s", "rows per panel", paste(rows, collapse = " ")))
writeLines(sprintf("%-18s: %d %d", "shared range", min(readings$v), max(readings$v)))
for (s in c("ALPHA", "BETA", "GAMMA")) {
r <- range(readings$v[readings$station == s])
writeLines(sprintf("%-18s: %d %d", paste("free range", s), r[1], r[2]))
}
writeLines(sprintf("%-18s: %s", "means whole",
if (isTRUE(all.equal(stats$mean, round(stats$mean)))) "TRUE" else "FALSE"))
Output:
STATION N MEAN MIN MAX
------------------------------
ALPHA 6 50 48 52
BETA 6 35 10 60
GAMMA 6 2 1 3
------------------------------
TOTAL 18
layers : 1
panels : 3
readings : 18
rows per panel : 6 6 6
shared range : 1 60
free range ALPHA : 48 52
free range BETA : 10 60
free range GAMMA : 1 3
means whole : TRUE
The structural facts are exactly what faceting promises. One geom_line gives one layer no matter how many panels; three stations give three panels; the eighteen readings partition six to a panel and sum back to eighteen. The summary table, computed with aggregate and printed by hand, shows three very different stations: ALPHA sits near 50 and barely moves, BETA climbs steadily from 10 to 60, and GAMMA hovers between 1 and 3. Read against the shared range of 1 to 60, those means and spans tell the true story.
The trouble is the scales = "free_y" on the facet. It hands each panel its own y axis, so ALPHA is drawn across 48 to 52, BETA across 10 to 60, and GAMMA across 1 to 3, each stretched to fill the same panel height. On the rendered dashboard all three lines then look equally dramatic: GAMMA's wander between 1 and 3, a span of 2, occupies as much vertical space as BETA's genuine climb of 50. A viewer glancing across the three panels concludes that all three stations are swinging hard, when in truth GAMMA is essentially flat and only BETA is moving.
Faceting itself has behaved perfectly -- the rows are partitioned correctly, the panels are labelled, the counts reconcile. The defect is a choice made on top of it, and it is the contact-sheet failure exactly: every frame re-exposed to look its best, so none can be compared. For a dashboard whose entire job is cross-station comparison, free scales are the wrong default; shared scales would show GAMMA as a nearly flat line hugging the bottom and BETA as the one real climber, which is the honest picture.
The free-scale deception is the first and worst flaw, but three more sit in this code. The means are computed without na.rm = TRUE, so a single missing reading would turn a station's whole summary line to NA while its panel still drew the surviving points -- a blank row under a populated panel, with no error raised. The stations are a plain character column, so the panels are ordered alphabetically, ALPHA then BETA then GAMMA, rather than by loudness or by any priority an operator would care about; the loud station is not first unless its name happens to sort first. And facet_wrap was left to choose its own row-and-column arrangement for three panels, so the layout is whatever the default decides -- fine here, but a plot meant to be stable across ggplot versions should set nrow or ncol explicitly rather than trust the default to stay put.
Common Mistakes
- Using
facet_gridwhenfacet_wrapwas meant, and getting a wall of empty panels.facet_grid(a ~ b)reserves a cell for every level combination, so faceting two variables with many sparse crossings produces mostly-empty panels. When you only want the combinations that occur,facet_wrap(~ a + b)drops the empty ones and keeps the plot readable.
- Leaving
scales = "free"on when panels must be compared. Free scales re-range each panel to its own data, so a tiny range and a huge range both fill their panel and look equally dramatic. Unless each panel is genuinely a separate story, keep the default shared scales, or the reader will compare heights that are not comparable.
- Facetting on a continuous variable.
facet_wrap(~ price)wherepricetakes hundreds of values makes hundreds of one-point panels. Faceting is for categorical splits; bin the variable first withcut()if you want panels by range, and map continuous variables to position or colour instead.
- Writing the
facet_gridformula backwards.facet_grid(rows ~ cols)puts the left variable down the rows and the right across the columns. Swapping them transposes the whole layout, andfacet_grid(. ~ x)versusfacet_grid(x ~ .)is the difference between a row of panels and a column of them -- easy to get backwards under time pressure.
- Forgetting the tilde, or the dot.
facet_wrap(region)is an error; it must befacet_wrap(~ region). Infacet_grida one-sided split still needs the placeholder:facet_grid(region ~ .)for rows orfacet_grid(. ~ region)for columns, and dropping the dot changes or breaks the layout.
- Assuming each panel gets its own legend or colour meaning. Faceting splits the data but keeps one shared legend and one shared set of scales, so a colour means the same thing in every panel. If you wanted a separate colour treatment per panel you have misunderstood faceting -- that is what separate plots, or a different aesthetic, are for.
- Letting alphabetical panel order stand in for a meaningful one. A character facet variable orders panels alphabetically, which rarely matches importance, time, or severity. Convert it to a factor with the levels in the order you want --
factor(station, levels = c(...))-- so the panels read in the order a human would choose.
- Relying on the default panel arrangement.
facet_wrappicks its ownnrowandncol, and that choice can shift between ggplot versions or as the number of levels changes. For any plot that must look the same twice, setnroworncolexplicitly rather than trusting the default to hold.
- Reading a free-scaled facet as if the axes matched. Even when free scales are the right choice, the panels are no longer directly comparable, and it is easy to forget that while looking at them. Label the axes clearly and state in the caption that scales are free, so no one mistakes a stretched small-range panel for a genuinely large swing.
Best Practices
- Reach for
facet_wrap(~ var)when splitting on one categorical variable with several levels, andfacet_grid(rows ~ cols)when the full matrix of two variables -- empty cells included -- is the message.
- Keep the default shared scales unless a panel is genuinely a separate story. Shared scales are what make faceting a fair comparison; reach for
scales = "free_*"deliberately and say so in the caption.
- Facet on categorical variables only. Bin a continuous variable with
cut()before faceting on it, so you get a handful of range panels rather than hundreds of single-point ones.
- Order panels on purpose by making the facet variable a factor with explicit
levels, so the panels read by time, size, or severity rather than by alphabet.
- Set
nroworncolonfacet_wrapfor any plot that must be reproducible, rather than letting the default arrangement drift between versions or level counts.
- Remember that faceting adds panels, not layers:
ggplot_build(p)$datastill has one entry per geom, and each layer's rows carry aPANELcolumn. Assert on those counts in tests rather than on the image.
- Use
labeller = label_bothwhen a bare level is ambiguous, so a panel reads "region: N" rather than just "N" and the reader knows what the split means.
- Keep the number of panels sane. Beyond a few dozen, a faceted plot becomes a texture rather than something a reader can scan; aggregate, filter, or split into several figures instead.
Practice Exercises
- You facet a plot with
facet_wrap(~ city)and get twelve panels, but you expected fifteen because the data covers fifteen cities. Explain why three panels are missing, how you would confirm which cities dropped out, and what you would use instead if you needed all fifteen shown including the empty ones.
- A colleague's faceted line chart uses
scales = "free_y"and every one of the eight panels looks equally volatile. Describe, in terms of per-panel data range versus shared range, why that appearance is misleading, and rewrite the facet call to make the eight panels honestly comparable.
- Given a data frame with columns
year(five values),quarter(four values), andsales, write thefacet_gridcall that puts years down the rows and quarters across the columns. State how many panels it produces and whatfacet_griddoes with a year-quarter pair that has no sales rows.
- A facet variable
gradeholds the character values "low", "medium", and "high", and the panels come out in the order high, low, medium. Explain why, and write the one line that reorders the panels to low, medium, high without touching any other part of the plot.