The Analogy: The Surveyor's Base Plan and Its Overlays
A land surveyor does not draw one finished picture. They pin a base sheet to the drafting table, mark the corner control points, and then work in transparent overlays -- one sheet of tracing film for the contour lines, another for the buildings, another for the drainage. Every overlay is registered to the same corner pins, so a point that sits at a given easting and northing lands on exactly the same spot whichever film it is drawn on. The finished drawing is the stack, read through from the top.
The pins are what make the overlays mean anything. An easting and a northing are just two numbers until the drawing says which axis each belongs to and what scale a millimetre on the film represents. Fix that once, on the base sheet, and every overlay inherits it: the contour drawn at a spot height and the building drawn at its corner are guaranteed to line up, because both were plotted against the same registration and the same scale. Change the scale on the base and every overlay moves together.
Some overlays trace measurements straight from the field book -- a building corner sits exactly where the chain and theodolite put it. Others are computed before they are drawn. A contour is not a measured line; it is interpolated from the scatter of spot heights, and a dot-density overlay showing trees per hectare is a count worked out from the raw marks, not a raw mark itself. Both kinds hang on the same pins, but one is the data as recorded and the other is the data after a calculation has been run over it.
The failure that ruins a survey drawing is the overlay that quietly loses a feature off the edge of the film. Suppose one spot height falls just outside the trimmed sheet and is clipped away before the contour overlay is computed. The contour is now interpolated from an incomplete set of heights, so it bends wrongly -- but the drawing looks finished, because the missing height left no mark to be missed. Nobody sees the gap; they see a clean, confident, subtly wrong line. In ggplot the pins are the coordinate system and scales, the overlays are the layers, the computed overlays are the statistical transformations, and the clipped spot height is a row dropped by a scale limit or a stat before it was ever drawn -- silently, with the plot looking complete.
Syntax or Core Structure
A ggplot is data, an aesthetic mapping, and one or more geoms added with +. The mapping is the registration: aes(x = dbh, y = ht) says which column is pinned to which axis. Because a plot is a picture, nothing here prints an image; instead ggplot_build() is used to reach the data frame the plot would draw, and its version-stable structural facts are read out with writeLines(). A rendered ggplot is never printed, and neither is any tibble.
library(ggplot2)
stand <- data.frame(
id = c("T1", "T2", "T3", "T4", "T5", "T6", "T7", "T8"),
dbh = c(22, 30, 16, 26, 18, 34, 20, 28),
ht = c(180, 200, 150, 190, 140, 210, 160, 200),
sp = c("oak", "oak", "pine", "oak", "pine", "birch", "pine", "birch"),
stringsAsFactors = FALSE
)
p <- ggplot(stand, aes(x = dbh, y = ht)) +
geom_point()
built <- ggplot_build(p)
d1 <- built$data[[1]]
writeLines(sprintf("%-16s: %d", "layers", length(built$data)))
writeLines(sprintf("%-16s: %d", "rows in layer", nrow(d1)))
writeLines(sprintf("%-16s: %s", "x is dbh", isTRUE(all.equal(d1$x, stand$dbh))))
writeLines(sprintf("%-16s: %s", "y is ht", isTRUE(all.equal(d1$y, stand$ht))))
writeLines(sprintf("%-16s: %d %d", "x range", min(stand$dbh), max(stand$dbh)))
writeLines(sprintf("%-16s: %d %d", "y range", min(stand$ht), max(stand$ht)))
writeLines(sprintf("%-16s: %d", "panels", length(unique(d1$PANEL))))
Output:
layers : 1
rows in layer : 8
x is dbh : TRUE
y is ht : TRUE
x range : 16 34
y range : 140 210
panels : 1
One geom means one layer, so built$data has length 1. That layer is a data frame with eight rows, one per tree, and its x and y columns are the dbh and ht values unchanged -- a plain geom_point neither summarises nor reorders, it just plots what it was given. Comparing the built x against stand$dbh with all.equal confirms the registration: the first column of the frame is pinned to the horizontal axis exactly as aes() asked.
Reading the ranges off the raw data rather than off the built scales is deliberate. A built panel carries an expanded range -- ggplot pads the axes so points do not sit on the frame edge -- and the size of that padding has changed between versions, so it is not a number to assert on. The row count, the column identity, and the single PANEL value are stable across versions; the exact axis limits are not. Throughout this lesson the rule is to check what the grammar guarantees and leave what the renderer decides to the renderer.
Technical Depth: Layers, Stats, and Mappings
The grammar has three moving parts that a beginner tends to blur together: a layer is an overlay, a stat is a computation run before drawing, and a mapping ties a column to a visual channel. The table names what each produces in the built data, which is what you can actually check.
| Grammar piece | What it is | Built-data effect |
|---|---|---|
| a geom | one drawn overlay | one entry in built$data |
geom_point | plots rows as given | x, y equal the mapped columns |
geom_bar | bars via stat_count | one row per category, y is a count |
geom_col | bars at a given height | y is the value you supplied |
a mapped aes | column to channel | a group and a colour per level |
| a set constant | fixed for the layer | one group, one constant value |
The two bar geoms are the classic confusion. geom_bar counts rows for you and its height is a computed number; geom_col draws the height you hand it. Reach for the wrong one and the bars are either counts you thought were sums or sums you thought were counts.
A second geom is a second overlay
means <- aggregate(dbh ~ sp, stand, mean)
p <- ggplot(stand, aes(x = sp, y = dbh)) +
geom_point() +
geom_point(data = means, size = 4, shape = 18)
built <- ggplot_build(p)
writeLines(sprintf("%-16s: %d", "layers", length(built$data)))
writeLines(sprintf("%-16s: %d", "point rows", nrow(built$data[[1]])))
writeLines(sprintf("%-16s: %d", "mean rows", nrow(built$data[[2]])))
writeLines(sprintf("%-16s: %s", "species", paste(means$sp, collapse = " ")))
writeLines(sprintf("%-16s: %s", "mean dbh", paste(means$dbh, collapse = " ")))
writeLines(sprintf("%-16s: %s", "means whole",
isTRUE(all.equal(means$dbh, round(means$dbh)))))
Output:
layers : 2
point rows : 8
mean rows : 3
species : birch oak pine
mean dbh : 31 26 18
means whole : TRUE
Two geom_point calls make two layers, and built$data now has length 2. The first overlay carries all eight trees; the second carries the three species means, computed by aggregate before the plot ever sees them, exactly like the surveyor's contour worked out before it is traced. The species come back in level order -- birch, oak, pine -- because a discrete axis sorts its categories, and the mean dbh values are whole numbers here by construction so there is nothing version-dependent to print. The second layer took its own data argument, which is how a computed overlay rides on the same pins as the raw one.
A stat computes the height; a column supplies it
bar <- ggplot(stand, aes(x = sp)) + geom_bar()
totals <- aggregate(dbh ~ sp, stand, sum)
col <- ggplot(totals, aes(x = sp, y = dbh)) + geom_col()
bd <- ggplot_build(bar)$data[[1]]
cd <- ggplot_build(col)$data[[1]]
writeLines(sprintf("%-16s: %d", "bar rows", nrow(bd)))
writeLines(sprintf("%-16s: %s", "bar x pos", paste(bd$x, collapse = " ")))
writeLines(sprintf("%-16s: %s", "stat_count", paste(bd$count, collapse = " ")))
writeLines(sprintf("%-16s: %d", "count total", sum(bd$count)))
writeLines(sprintf("%-16s: %s", "col heights", paste(cd$y, collapse = " ")))
writeLines(sprintf("%-16s: %d", "height total", sum(cd$y)))
writeLines(sprintf("%-16s: %s", "count is nrow", sum(bd$count) == nrow(stand)))
Output:
bar rows : 3
bar x pos : 1 2 3
stat_count : 2 3 3
count total : 8
col heights : 62 78 54
height total : 194
count is nrow : TRUE
geom_bar ran stat_count and turned eight rows into three, one per species, with a count column that adds back to the eight trees that went in. The discrete axis positions those three bars at 1, 2, 3. geom_col did no counting: handed a frame of per-species total dbh, it drew bars at exactly those heights, 62, 78, 54, which sum to the total dbh of the stand. The same three species, two completely different y columns -- a count you did not compute and a sum you did. Choosing the geom is choosing whether the stat runs.
Mapping makes groups; setting does not
mapped <- ggplot(stand, aes(x = dbh, y = ht, colour = sp)) + geom_point()
set <- ggplot(stand, aes(x = dbh, y = ht)) + geom_point(colour = "red")
md <- ggplot_build(mapped)$data[[1]]
sd <- ggplot_build(set)$data[[1]]
writeLines(sprintf("%-16s: %d", "mapped groups", length(unique(md$group))))
writeLines(sprintf("%-16s: %d", "mapped colours", length(unique(md$colour))))
writeLines(sprintf("%-16s: %d", "set groups", length(unique(sd$group))))
writeLines(sprintf("%-16s: %s", "set colour", unique(sd$colour)))
writeLines(sprintf("%-16s: %d", "set colours", length(unique(sd$colour))))
writeLines(sprintf("%-16s: %d", "continuous grp", unique(ggplot_build(
ggplot(stand, aes(x = dbh, y = ht, colour = dbh)) + geom_point())$data[[1]]$group))
)
Output:
mapped groups : 3
mapped colours : 3
set groups : 1
set colour : red
set colours : 1
continuous grp : -1
Mapping colour = sp inside aes() splits the layer into three groups, one per species, and assigns three distinct colours -- the built data carries a group and a colour column that prove it. Setting colour = "red" outside aes() does the opposite: one group, one colour, applied to every point as a constant. The distinction is the single most common ggplot error, and it is why colour that should vary sits stubbornly uniform, or colour that should be fixed turns into an unwanted legend. The last line adds the subtlety: mapping a continuous column gives a group of -1, ggplot's marker for no discrete grouping, because a gradient is one continuous scale rather than a set of levels.
Real World Example: A Forest Survey Scatter
Eighteen trees are surveyed across three species, each with a diameter at breast height and a total height. The plan is a scatter of every tree with a bold overlay marking each species mean, and the questions are the ones the grammar can answer without a picture: how many overlays, how many rows in each, and -- because points overlap -- how many trees the scatter can actually show.
library(ggplot2)
survey <- data.frame(
id = sprintf("%s%d", rep(c("O", "P", "B"), each = 6), rep(1:6, 3)),
sp = rep(c("oak", "pine", "birch"), each = 6),
dbh = c(22, 24, 26, 28, 24, 26,
16, 18, 20, 16, 18, 20,
30, 34, 32, 36, 30, 36),
ht = c(180, 185, 195, 200, 185, 195,
140, 150, 160, 140, 150, 160,
200, 205, 205, 210, 200, 210),
stringsAsFactors = FALSE
)
means <- aggregate(cbind(dbh, ht) ~ sp, survey, mean)
p <- ggplot(survey, aes(x = dbh, y = ht, colour = sp)) +
geom_point() +
geom_point(data = means, size = 5, shape = 18)
built <- ggplot_build(p)
raw <- built$data[[1]]
distinct_pts <- nrow(unique(survey[c("sp", "dbh", "ht")]))
writeLines(sprintf("%-8s%4s%9s%8s", "SPECIES", "N", "MEANDBH", "MEANHT"))
writeLines(strrep("-", 29))
for (i in seq_len(nrow(means))) {
cnt <- sum(survey$sp == means$sp[i])
writeLines(sprintf("%-8s%4d%9d%8d", means$sp[i], cnt, means$dbh[i], means$ht[i]))
}
writeLines(strrep("-", 29))
writeLines(sprintf("%-8s%4d", "TOTAL", nrow(survey)))
writeLines("")
writeLines(sprintf("%-18s: %d", "layers", length(built$data)))
writeLines(sprintf("%-18s: %d", "tree rows", nrow(built$data[[1]])))
writeLines(sprintf("%-18s: %d", "mean rows", nrow(built$data[[2]])))
writeLines(sprintf("%-18s: %d %d", "dbh range", min(survey$dbh), max(survey$dbh)))
writeLines(sprintf("%-18s: %d %d", "ht range", min(survey$ht), max(survey$ht)))
writeLines(sprintf("%-18s: %d", "colour groups", length(unique(raw$group))))
writeLines(sprintf("%-18s: %d", "distinct points", distinct_pts))
writeLines(sprintf("%-18s: %d", "hidden by overlap", nrow(survey) - distinct_pts))
writeLines(sprintf("%-18s: %s", "means whole",
isTRUE(all.equal(unlist(means[c("dbh", "ht")]),
round(unlist(means[c("dbh", "ht")]))))))
Output:
SPECIES N MEANDBH MEANHT
-----------------------------
birch 6 33 205
oak 6 25 190
pine 6 18 150
-----------------------------
TOTAL 18
layers : 2
tree rows : 18
mean rows : 3
dbh range : 16 36
ht range : 140 210
colour groups : 3
distinct points : 11
hidden by overlap : 7
means whole : TRUE
The plot is two overlays on one set of pins. The first geom_point carries all eighteen trees, the second carries the three means from aggregate, and built$data has length 2 to match. The summary table is computed in base R and printed by hand, one row per species with its count and its mean dbh and height; the means are whole numbers by construction, so there is nothing here that a different ggplot version would round differently. Colour is mapped to species, so the raw layer splits into three groups, exactly as the earlier example showed.
The line that earns its place is hidden by overlap. The scatter has eighteen trees but only eleven distinct (sp, dbh, ht) positions, so seven points are drawn precisely on top of a point already there and add nothing the eye can see. ggplot_build still reports eighteen rows in the layer -- the data is all present -- but the picture shows eleven marks. This is the survey overlay whose features stack on the same spot: the drawing looks sparse when the stand is dense, and no warning is raised because nothing was dropped, only overplotted.
That overplotting is the first real flaw, and it is not cosmetic. A reader counts marks and concludes the plot holds eleven trees, or judges pine less common than it is, because six pine records collapse onto three visible points. The honest fixes -- a jitter, an alpha below one, or a count mapped to size -- all change the picture the code draws; the code as written quietly under-reports its own sample. Worse, every overlap here is within a single species, so colour cannot rescue it: two pine points on the same spot are the same colour and merge completely.
Three further weaknesses hide in the same script. The means are computed without na.rm, so a single missing dbh or ht would turn that species mean into NA and drop its diamond from the overlay while its raw points stayed on the plot -- a bold marker silently missing, with the scatter beneath it intact and no error printed. The mean overlay itself compresses a whole species to one point, so the spread that matters to a forester -- are the oaks uniform or split into two age classes -- is thrown away exactly where the eye is drawn. And colour is mapped to sp with no explicit scale, so the palette is whatever ggplot's default happens to be that version; a plot meant for print should name its colours rather than inherit them, or two builds will not match.
Common Mistakes
- Putting a constant inside
aes(). Writingaes(colour = "blue")does not paint the points blue; it maps every row to the literal string "blue", builds a one-level legend, and fills it with ggplot's first default hue, a salmon red. A constant that should apply to the whole layer belongs outsideaes(), asgeom_point(colour = "blue"). This one error accounts for more confused ggplot questions than any other.
- Joining layers with the pipe instead of
+. A ggplot is assembled with+, not%>%or the native|>. Piping a plot into a geom --ggplot(df, aes(x, y)) %>% geom_point()-- raises "cannot add ... to a ggplot object" at best, and at worst does something unintended. Use the pipe to prepare the data, then start a fresh+chain for the plot.
- Reaching for
geom_bar()when the heights are already computed.geom_bar()runsstat_countand tallies rows, so if your frame already holds the totals you want as bar heights, every bar comes out as 1. Usegeom_col()(orgeom_bar(stat = "identity")) to takeyas given, and reservegeom_bar()for when you genuinely want ggplot to count.
- Forgetting that a plot is an object that must be printed.
p + geom_line()returns a new object; if you neither reassign nor print it, the layer vanishes. Inside aforloop orlapply, a bareggplot(...)call is built but never rendered because auto-printing only happens at the top level -- you must callprint(p)explicitly to see each panel.
- Confusing a continuous mapping with a discrete one.
colour = cylmaps a number to a smooth gradient;colour = factor(cyl)maps it to distinct swatches with a categorical legend. Pick the wrong one and you get a gradient over categories that have no order, or a legend with hundreds of entries because a continuous key was treated as a factor.
- Drawing dense scatters at full opacity. Thousands of points at
alpha = 1pile into a solid blob that hides how many observations sit underneath. Overplotting is silent -- no warning fires because nothing is dropped -- so a plot can look sparse while the data is dense. Reach foralpha,position_jitter, orgeom_hexbefore trusting a crowded scatter.
- Trusting the default palette to carry meaning. The default hue scale is decorative and not colour-blind safe; using it to encode an ordered or safety-critical variable misleads roughly one reader in twelve, and its colours are not perceptually uniform. For any colour that means something, set an explicit
scale_colour_viridis_*or a named ColorBrewer palette.
- Ignoring the "Removed N rows containing missing values" warning. When a mapped column holds
NA, ggplot silently drops those rows and prints a one-line warning that is easy to scroll past. The plot then represents fewer observations than the data holds, and a summary layer computed withoutna.rm = TRUEcan showNAor shift a mean. Treat that warning as a question about your data, not noise.
- Feeding ggplot something that is not a tidy data frame.
ggplot(data = )expects a data frame or tibble with named columns, one row per observation. A matrix, a bare vector, or atableobject will not map cleanly, and wide data with one column per series must be reshaped withpivot_longer()first so that the series becomes a single grouping column the grammar can map.
Best Practices
- Map variables inside
aes()and set constants outside it. This single rule -- mapping means "let this column decide", setting means "make it exactly this" -- prevents the most common ggplot mistake and makes every layer's intent unambiguous.
- Assign the plot to an object and build it incrementally:
p <- ggplot(df, aes(...)), then add geoms and scales. An object can be inspected, reused across outputs, and interrogated withggplot_build(), which a one-shot expression cannot.
- Reshape to tidy long form before plotting -- one row per observation, one column per variable -- and let
aes()do the mapping.pivot_longer()turns three measurement columns into a grouping key and a value, which is exactly what the grammar wants.
- Be explicit about counting:
geom_col()for heights you have already computed,geom_bar()only when you want ggplot to tally rows. Stating which you mean stops the "every bar is 1" surprise.
- Address overplotting deliberately with
alpha,position_jitter, or a binning geom such asgeom_hexandgeom_bin2d, rather than trusting that a dense scatter shows its true weight.
- Choose a colour-blind-safe, perceptually uniform scale (viridis, or a named ColorBrewer palette) and set it explicitly for any colour that encodes meaning, so the plot reads correctly in print and for every viewer.
- Label the plot fully with
labs(title =, x =, y =, colour =)so it stands on its own. A figure that needs the source code to be understood is not finished.
- In tests and reproducible reports, assert on
ggplot_build(p)$data-- layer count, per-layer row counts, computed stats -- rather than on the rendered image. Those structural facts are stable across ggplot versions; pixels and axis expansion are not.
Practice Exercises
- You have a data frame with columns
date,city, andtempholding daily readings for three cities. Build a line plot oftempagainstdatewith one coloured line per city. State exactly which column you map tocolour, why that mapping must sit insideaes(), and what would happen if you wrotecolour = "city"as a constant instead.
- A summary table has columns
regionandtotal_sales, already aggregated so each region appears once. Draw a bar chart whose bar heights equaltotal_sales. Explain whygeom_col()is the correct geom here and describe precisely whatgeom_bar()would draw instead if you used it by mistake.
- A scatter of five thousand points renders as a solid blob. Rewrite it three ways -- once with
alphabelow one, once withposition_jitter, and once withgeom_hex-- and for each, describe what structure it reveals that the naive full-opacity plot hid.
- Given
p <- ggplot(df, aes(x, y, colour = grp)) + geom_point() + geom_smooth(), useggplot_build(p)to report how many layers the plot has, how many rows the point layer holds, and how many rows the smooth layer holds. Write down your predicted numbers before you run it, then reconcile any difference.