14 Visualization and the Grammar of Graphics
14.1 Prerequisites
Answer the following questions to see if you can bypass this chapter. You can find the answers at the end of the chapter in Section 14.20.
- Name the seven main components of a statistical plot according to the Grammar of Graphics.
- In
ggplot2, what does an aesthetic mapping (aes()) specify? - What is the primary advantage of the Grammar of Graphics approach compared with traditional per-chart-type plotting functions?
14.2 Learning objectives
By the end of this chapter you should be able to:
- State the components of the grammar of graphics: data, aesthetic mapping, geom, stat, scale, coord, facet.
- Build a plot with
ggplot2by composing layers. - Choose an appropriate geom for a given combination of variable types (continuous-continuous, continuous-discrete, discrete-discrete, count, time, etc.).
- Apply scales for color, fill, size, and shape, including color-blind-safe palettes.
- Use facets to display the same plot conditioned on a third variable.
- Recognize and avoid common visualization errors: truncated axes, dual y-axes, double-encoding, default rainbow color scales, pie charts.
- Distinguish ‘good plots’ (one message, truthful, clear encoding) from ‘bad plots’ that decorate rather than communicate.
14.3 Orientation
A good plot conveys a single message quickly and truthfully. A bad plot does neither. Either it decorates without communicating, or it communicates a wrong impression of the data.
Leland Wilkinson codified the Grammar of Graphics, and Hadley Wickham implemented it for R as ggplot2. The grammar makes the structure of a plot explicit. Every plot is a composition of seven kinds of element: data, aesthetic mappings, geoms, stats, scales, a coordinate system, and facets. Once we think in these pieces, the universe of statistical graphics becomes a small set of swappable parts rather than a zoo of named chart types.
In this chapter we shall present the grammar conceptually and then apply it through ggplot2. We begin with the judgments that remain with the analyst, and then take the seven components in turn, with sections on geoms, stats, scales, and facets. We close with common mistakes, themes and labels, and saving plots. The next chapter goes deeper on advanced ggplot techniques (themes, extensions, interactivity).
14.4 The statistician’s contribution
Software can produce a plot from any data. It cannot choose what plot to make.
Pick the right encoding. Continuous values map well to position (x, y, length). Categorical values map well to color, shape, or facets. Mapping a many-level categorical variable to shape (10 different shapes for 10 levels) creates an unreadable plot, and ggplot2 refuses to map a continuous variable to shape at all. Mapping a categorical variable to a sequential color scale implies an ordering that may not exist. The grammar makes these mistakes structurally visible, because each aesthetic has a natural variable type.
One plot, one message. A figure that crams in three relationships is harder to read than three figures that each show one. The temptation to combine is strong. Nevertheless, the clarity gained by separating is usually worth more than the space saved.
Truthful axes. Truncating a y-axis to make a small difference look large is dishonest. Logarithmic axes without a clear visual cue mislead readers who do not notice the transformation. Axes should encode what they appear to encode.
Accessible color. Roughly 8% of men and 0.5% of women have some form of color vision deficiency. The default ggplot2 palettes (and most journal defaults) are not color-blind-safe. The viridis, RColorBrewer, and ggthemes palettes include accessible options. Choosing one takes about thirty seconds, and it keeps the plot legible to a substantially larger audience.
These judgments are not automatable. The grammar makes them easier to think about by structuring the plot into separable decisions, which we now take up one at a time.
14.5 The grammar of graphics: seven components
A plot is the composition of the following seven components.
- Data. A data frame (or tibble). The plot is a view of these data.
- Aesthetic mappings. Which columns of the data map to which visual properties (x-position, y-position, color, shape, size, fill, alpha).
- Geoms (geometric objects). What is drawn at each data point: a point, a line, a bar, a polygon, a tile.
- Stats (statistical transformations). Whether the data are drawn as-is or first summarized: smoothed, binned into histograms, summarized by mean and SE.
- Scales. How aesthetic values are translated to pixels: which range of x-values maps to which pixels; which colors encode which categories.
- Coordinate system. Cartesian (default), polar, geographic, transformed (log, sqrt).
- Facets. Whether the plot is split into a grid of subplots conditioned on a categorical variable.
Every ggplot() call is some combination of these. Most calls touch only a few, and the others take sensible defaults.
14.6 A minimum-viable example
To illustrate, consider the Palmer penguins data and the relationship between flipper length and body mass.
library(ggplot2)
library(palmerpenguins)
p <- penguins |>
na.omit() |>
ggplot(aes(x = flipper_length_mm,
y = body_mass_g,
colour = species)) +
geom_point(alpha = 0.7) +
scale_colour_brewer(palette = "Dark2") +
labs(x = "Flipper length (mm)",
y = "Body mass (g)",
colour = "Species") +
theme_minimal()
pWe may read off each piece of the grammar from the call.
penguins |> na.omit()is the data.aes(x = ..., y = ..., colour = ...)is the aesthetic mapping: three data columns mapped to three visual properties.geom_point(alpha = 0.7)is the geom: each row gets a semi-transparent point.scale_colour_brewer(...)is the scale: how species values map to colors (Dark2 is color-blind-safe).labs(...)andtheme_minimal()provide labels and a visual style.- No explicit stat because
geom_pointdefaults tostat_identity(no transformation). - No coord because
coord_cartesianis the default. - No facet because we are showing all data in one panel.
The plot is built by adding layers with +. Each layer may override the inherited mapping, change the geom, add a stat, or modify the appearance.
14.7 Geoms by variable types
The choice of geom is largely determined by the types of the x and y variables. The table below gives the common choices.
| x type | y type | Common geoms |
|---|---|---|
| continuous | continuous | geom_point, geom_smooth, geom_density_2d |
| continuous | discrete | geom_boxplot (with coord_flip), geom_violin |
| discrete | continuous | geom_boxplot, geom_violin, geom_point (jittered), geom_col |
| discrete | discrete | geom_count, geom_tile (heatmap) |
| time | continuous | geom_line, geom_step, geom_area |
| (1 var) | (1 var) | geom_histogram, geom_density, geom_bar |
For two-variable scatterplots with thousands of points, overlap obscures the pattern. There are three standard remedies.
geom_point(alpha = 0.05) # transparency
geom_hex(bins = 50) # hexagonal binning
geom_density_2d_filled() # 2D density contoursViolins and boxplots combine naturally.
ggplot(penguins, aes(x = species, y = body_mass_g)) +
geom_violin(fill = "lightgray") +
geom_boxplot(width = 0.1) +
geom_jitter(width = 0.1, alpha = 0.4)Geoms may be layered freely. However, the order matters, since later layers paint over earlier ones.
14.8 Statistical transformations
Geoms may summarize the data before drawing. The summary is controlled by the stat argument or by the geom itself.
# raw points (stat_identity, the default)
ggplot(penguins, aes(flipper_length_mm, body_mass_g)) +
geom_point()
# linear smooth with 95% CI
ggplot(penguins, aes(flipper_length_mm, body_mass_g)) +
geom_point() +
geom_smooth(method = "lm", formula = y ~ x)
# loess smooth (default for n < 1000)
ggplot(penguins, aes(flipper_length_mm, body_mass_g)) +
geom_point() +
geom_smooth()
# group means with SE
ggplot(penguins, aes(species, body_mass_g)) +
stat_summary(fun.data = mean_se)
# histogram (stat_bin)
ggplot(penguins, aes(body_mass_g)) +
geom_histogram(bins = 30)geom_smooth(method = "lm") fits a linear model per group (if the aesthetic includes colour or group) and plots the fitted line with a confidence band. For regression visualization, this single line of code does what would take many lines in base R.
14.9 Scales
Scales control how aesthetic values map to visual properties. The defaults are reasonable but rarely optimal. We give the common forms for continuous axes, discrete axes, and color.
Continuous axes:
scale_x_continuous(breaks = seq(0, 100, 25),
labels = scales::number_format(suffix = "%"),
limits = c(0, 100))
scale_y_log10() # log-transformed y axis
scale_x_sqrt() # square-root transformedDiscrete axes:
scale_x_discrete(limits = c("placebo", "low", "high")) # custom orderColor:
scale_colour_brewer(palette = "Dark2") # color-blind safe, qualitative
scale_colour_viridis_d() # color-blind safe, ordered
scale_colour_manual(values = c("a" = "red", "b" = "blue"))
scale_colour_gradient(low = "white", high = "darkblue") # continuousviridis and ColorBrewer’s qualitative palettes (Dark2, Set1, Set2) are the standard color-blind-safe defaults. We would avoid the rainbow scale (jet, rainbow()) for continuous data. It is not perceptually uniform, and many readers find it unreadable.
The choice of palette follows the structure of the data. For discrete fills with no natural order, a qualitative palette is appropriate. For ordered discrete or continuous data, viridis or a sequential ColorBrewer palette (Blues, Reds, etc.) is the usual choice. For diverging data (positive vs. negative), we use a diverging palette (RdBu, PuOr).
14.10 Faceting
Facets split the plot into a grid of small multiples by one or two variables.
# rows = species, columns = sex
ggplot(penguins, aes(flipper_length_mm, body_mass_g)) +
geom_point() +
facet_grid(species ~ sex)
# wrap into a single dimension
ggplot(penguins, aes(flipper_length_mm, body_mass_g)) +
geom_point() +
facet_wrap(~ species, ncol = 1)Faceting lets us condition on a third (or fourth) variable without losing the underlying plot’s design. It is particularly useful for displaying group-specific patterns when the groups are too many or too small for color-coding to be readable.
14.11 Common mistakes
A small number of mistakes account for most misleading statistical graphics. We list them here.
Truncated axes. Setting ylim() to exclude zero on a bar chart exaggerates differences. Setting it to exclude the data range entirely is misleading.
Dual y-axes. Two y-axes on different scales nearly always mislead. Readers cannot tell at a glance which trace corresponds to which axis. Two facets are a better choice.
Pie charts beyond two categories. Humans read angles poorly. A bar chart of the same data is universally clearer.
Default color for ordered categories. The ggplot2 default scale_colour_discrete is unordered. If the categories are ordered (e.g., low/medium/high), we would use scale_colour_viridis_d() or a sequential ColorBrewer palette to encode the ordering visually.
3D plots. A 3D plot is almost always worse than a 2D plot with a color or size encoding.
Over-the-top legends. A legend that explains 10 categories with 10 colors and 10 shapes triple-encodes the same information. One encoding is enough.
14.12 Themes and labels
Themes control the non-data appearance of a plot, such as backgrounds, grids, and fonts. The built-in themes include theme_grey() (the default), theme_minimal(), theme_bw(), and theme_classic(). We recommend choosing one and using it consistently across a paper or report.
ggplot(penguins, aes(flipper_length_mm, body_mass_g)) +
geom_point() +
labs(title = "Body mass vs. flipper length",
subtitle = "Palmer Archipelago penguins, 2007-2009",
x = "Flipper length (mm)",
y = "Body mass (g)",
caption = "Source: palmerpenguins package") +
theme_minimal()Axes should always be labeled with units. ‘Body mass (g)’ tells the reader more than ‘body_mass_g’. A caption that cites the data source also earns the reader’s trust.
14.13 Saving plots
ggsave() writes a plot to disk in raster or vector form.
ggsave("flipper_mass.png", plot = p, width = 6, height = 4,
dpi = 300, units = "in")
# vector format for publication
ggsave("flipper_mass.pdf", plot = p, width = 6, height = 4)For papers we use vector formats (PDF, SVG) when possible, since they remain crisp at any zoom. For the web, PNG at moderate DPI is a good default. JPG should be avoided for plots, because its compression artifacts are visible on lines and text.
14.14 Collaborating with an LLM on visualization
LLMs handle ggplot2 code well. They handle visualization judgment less reliably.
Prompt 1: drafting a plot. Describe the data and the question. Ask: ‘write a ggplot2 plot that addresses the question. Use a color-blind-safe palette and label axes with units.’
What to watch for. The default LLM plot tends to be busy. It encodes too many aesthetics, keeps the default ggplot theme, and sometimes omits axis labels. We would push for clarity over decoration. Several rounds of asking for something ‘simpler’ tend to improve the result.
Verification. Render the plot and ask whether a reader who has never seen the data could state its message in one sentence. If not, simplify.
Prompt 2: critiquing a plot. Paste a ggplot() call and the rendered plot description, and ask: ‘critique this plot, what would be unclear or misleading to a reader?’
What to watch for. LLMs are reasonably good at spotting truncated axes, dual y-axes, missing labels, and palette issues. They are weaker on subject-matter problems, such as the wrong choice of summary or a scale inappropriate to the units. Here the analyst has to supply the substantive judgment.
Verification. Apply the suggested fixes, render the plot, and compare the before and after versions.
Prompt 3: replicating a published plot. Describe a target figure (or paste the published plot if available) and ask the LLM to reproduce its design.
What to watch for. LLMs can reproduce the visual style of well-known plots (Tufte, Minard). They cannot read our data and decide whether the same design fits it. We treat the LLM output as a starting point and adapt it to the data at hand.
Verification. Compare the result with the original. Are the encodings the same? Is the aspect ratio? Are the colors? Differences may be improvements, or they may be regressions.
14.15 Principle in use
Three habits define defensible visualization:
- One plot, one message. Resist the urge to combine three relationships into one figure. Three figures with one message each are clearer.
- Truthful axes, accessible colors. Avoid truncated axes that exaggerate differences, color palettes that exclude color-blind readers, and dual y-axes that mislead by their scale.
- Compositional thinking. Build plots by combining grammar pieces, not by reaching for chart types. The right plot for an unusual question is rarely a built-in chart. It is usually a small variation on something familiar.
14.16 Version notes (ggplot2 3.5+)
A few legacy patterns no longer work in current ggplot2. aes_string() is soft-deprecated in ggplot2 3.5+. For programmatic aesthetics we use the .data and .env pronouns from rlang instead, e.g., aes(x = .data[[varname]]). qplot() has been deprecated since ggplot2 3.4.0, and ggplot() should be used directly. When older code or LLM output uses these constructs, we translate them to the current forms before relying on the result.
14.17 Exercises
- Reproduce the penguin body-mass-vs-flipper-length scatter plot from
palmerpenguins, colored by species, faceted by island. Add a regression line and a 95% confidence band per species. - Take a bad plot from a recent newspaper article (or social media). Identify three things wrong with it. Rewrite it in
ggplot2to fix them. - Use
ggplot2::aes()to map the same variable to two different aesthetics (e.g., color and shape). Argue for or against this as a design choice with reference to the encoding principles in this chapter. - Take a dataset with 100,000+ rows. Make a scatter plot that does not suffer from overplotting. Compare three approaches: alpha, hex binning, and 2D density contours. Which works best for the data?
- Make a
facet_wrapplot with too many panels (say, 30 for 30 patients in a longitudinal study). Identify what goes wrong, and propose two alternatives:facet_wrapwith a different ordering, or a different plot entirely.
14.18 Further reading
- (Wickham, 2016), canonical
ggplot2reference; the 3rd edition is online at https://ggplot2-book.org/. - (Wilke, 2019), principles of effective visualization, with every figure built in R.
- (Tufte, 2001), the foundational text on information design.
- (Healy, 2018), shorter, applied, with R code; a good complement to Wickham’s reference.
14.19 Practice test
The following multiple-choice questions exercise the chapter’s content. Attempt each question before expanding the answer.
14.19.1 Question 1
According to the Grammar of Graphics framework, which of the following is NOT one of the seven main components of a plot?
- Data
- Aesthetics
- Colors
- Facets
C. Color is a specific aesthetic, not a component of the grammar.
14.19.2 Question 2
In ggplot2, what does the aesthetic mapping specify?
- The color scheme to use for the plot
- How variables in the data are mapped to visual properties
- The size of the plot window
- The theme and style of the plot
B. aes() maps data columns to visual properties such as x, y, color, shape, size.
14.19.3 Question 3
What is the main advantage of the Grammar of Graphics approach compared to traditional plotting approaches?
- It produces more colorful plots
- It renders plots faster
- It provides a systematic way to describe and create visualizations
- It requires less code to create simple plots
C. The grammar is compositional: new plots are assembled from a small set of reusable pieces.
14.19.4 Question 4
A bar chart shows treatment success rates of 75% (control) and 78% (treatment). The y-axis runs from 70% to 80%. The visual impression is misleading because:
- The colors are unreadable.
- The y-axis is truncated, exaggerating the difference.
- Bar charts are inherently misleading.
- The font size is too small.
B. For bar charts, the y-axis should start at 0 (or span symmetrically across zero for negative values). Truncation makes a 3-point difference look much larger.
14.19.5 Question 5
You are encoding species (3 categories) on a scatter plot. Which scale is most appropriate?
scale_colour_continuous()with a viridis ramp
scale_colour_brewer(palette = "Dark2")
scale_colour_gradient(low, high)
- Default ggplot2 colors
B. Three unordered categories call for a qualitative color-blind-safe palette, and Dark2 (or Set2 / viridis_d) fits the role. Continuous scales imply an ordering that species do not have. The ggplot2 defaults are not color-blind-safe.
14.20 Prerequisites answers
- Data, aesthetic mappings, geometries (geoms), statistical transformations (stats), scales, coordinate system, and faceting. Note that colors is a specific aesthetic, not one of the seven components.
- An aesthetic mapping specifies how a variable in the data is mapped to a visual property of the plot (x-position, y-position, color, shape, size, etc.). The grammar enforces a strict separation between data (what) and visual encoding (how it appears).
- The grammar provides a systematic, compositional way to describe and create visualizations. New plots are built by swapping or layering grammar components, rather than by learning a different function for every chart type. The benefit is that the same vocabulary covers everything from a histogram to a Sankey diagram to a custom map.