8  Plotting with ggplot2

NoteWhat you’ll be able to do

By the end of this chapter you will be able to:

  1. Build a plot from the grammar of graphics: data, aesthetics, geom layers.
  2. Create scatterplots, boxplots, bar charts, and histograms.
  3. Choose between bars and boxplots for group comparisons — and say why.
  4. Identify misleading-graph features (truncated axes, hidden distributions) using the gallery.
  5. Save a publication-quality plot with ggsave().

R has two main plotting systems. Base R graphics (the plot(), hist(), boxplot() functions you already saw in Chapter 3) are quick and convenient for one-off exploration. ggplot2 is more code per plot, but it produces publication-quality output and scales gracefully to complicated displays. This book uses both: base R for quick EDA, ggplot2 for anything you’d share or publish.

This chapter introduces the grammar of graphics that ggplot2 is built on, and walks you through the four chart types you’ll use most.

8.1 The grammar of graphics

The name ggplot2 comes from grammar of graphics, an idea developed by Leland Wilkinson. The premise is that any statistical chart can be built up from a small set of components combined in predictable ways:

  1. Data — the dataset you’re plotting.
  2. Aesthetics — the mappings from variables in your data to visual properties on the plot (which variable goes on the x-axis, which to color by, etc.).
  3. Geoms — the geometric objects that represent the data (points, lines, bars, boxes).
  4. Optional layers — labels, scales, themes, facets that polish the result.

Every ggplot you write is data + aesthetics + geoms, with optional layers stacked on top using +.

ggplot(data, aes(x = variable1, y = variable2)) +
  geom_point()

That code says: take this dataset, map variable1 to the x-axis and variable2 to the y-axis, and represent each observation as a point.

8.2 Setup

ggplot2 is part of the install bundle from Chapter 6, so if you ran that in this project it’s already installed. Packages install once per project in Posit Cloud; in a new project, install it first:

install.packages("ggplot2")

You have to load it once per R session:

library(ggplot2)

A common shortcut is to load the entire tidyverse, which bundles ggplot2 together with several other useful packages:

library(tidyverse)

The examples below use the penguins dataset (from the palmerpenguins package) — measurements of bill length, bill depth, flipper length, body mass, and species for penguins from three islands in Antarctica. If you don’t have it loaded yet:

install.packages("palmerpenguins")
library(palmerpenguins)
data(penguins)
penguins <- na.omit(penguins)  # drops 11 rows; fine here only because no plot uses sex,
                               # the column most of them are missing (see @sec-preparing-data)
WarningDon’t skip library(palmerpenguins)

Recent versions of R (4.5 and later) include their own built-in penguins dataset with different column names — bill_len instead of bill_length_mm, and so on. If you skip library(palmerpenguins), R quietly hands you the built-in version, and every example below fails with an error like object 'bill_length_mm' not found. Run names(penguins): you want to see bill_length_mm.

8.3 Scatter plots

Scatter plots show the relationship between two continuous variables — the workhorse chart of regression and correlation.

8.3.1 Basic scatter

ggplot(penguins, aes(x = bill_length_mm, y = bill_depth_mm)) +
  geom_point()

ggplot() initializes the plot, aes() defines the mappings, geom_point() adds the points.

8.3.2 Add color for a categorical variable

ggplot(penguins, aes(x = bill_length_mm,
                     y = bill_depth_mm,
                     color = species)) +
  geom_point()

color = species tells ggplot to color each point by species. R will pick a default palette and add a legend automatically.

8.3.3 Add labels and a title

ggplot(penguins, aes(x = bill_length_mm,
                     y = bill_depth_mm,
                     color = species)) +
  geom_point() +
  labs(title = "Bill Length vs. Bill Depth",
       x = "Bill Length (mm)",
       y = "Bill Depth (mm)",
       color = "Species")

labs() controls everything text-related: title, subtitle, axis labels, and legend labels.

8.4 Box plots

Box plots show the distribution of a continuous variable across categories. They’re the right chart for any between-groups comparison, like an independent-samples t-test or a one-way ANOVA. For paired or repeated-measures data, side-by-side boxes hide which scores belong to the same person. Connect each person’s scores with a line, or plot the difference scores instead (Chapter 16).

8.4.1 Basic box plot

ggplot(penguins, aes(x = species, y = flipper_length_mm)) +
  geom_boxplot()

8.4.2 Fill by group

ggplot(penguins, aes(x = species,
                     y = flipper_length_mm,
                     fill = species)) +
  geom_boxplot()

fill colors the interior of the box, color colors the outline. For a box plot you usually want fill.

8.4.3 Add notches for a rough significance check

ggplot(penguins, aes(x = species,
                     y = flipper_length_mm,
                     fill = species)) +
  geom_boxplot(notch = TRUE)

Notches span roughly \(\pm 1.58 \times \text{IQR}/\sqrt{n}\) around the median — a rough visual aid for comparing medians, not a true 95% confidence interval. If notches between two boxes do not overlap, you have rough visual evidence that the medians differ. This is not a substitute for a real test — but it’s a useful eyeball check during EDA.

8.5 Bar charts

Bar charts compare counts or summary statistics across categories.

8.5.1 Bar chart of counts

ggplot(penguins, aes(x = species)) +
  geom_bar()

geom_bar() by default counts the rows in each category — you don’t need to compute counts yourself.

8.5.2 Bar chart of group means

ggplot(penguins, aes(x = species, y = flipper_length_mm)) +
  stat_summary(fun = "mean", geom = "bar")

stat_summary() computes a summary (here, the mean) and draws a bar of that height. You can change fun = "mean" to "median", "sd", etc.

WarningBars vs. boxes for group comparisons

For comparing groups, a box plot is almost always better than a bar plot of means. A bar of means hides the distribution entirely; a box plot shows the median, the IQR, and outliers. The popular “bar chart with error bars” hides even more by reducing each group to two numbers: a mean and an error bar. The error bar might be the SD, the SE, or a confidence interval, and figures often don’t say which. The format is particularly misleading when distributions are skewed. Default to box plots for comparing groups in EDA; reserve bar charts for counts or proportions.

8.6 Histograms

You’ll mostly use hist() from base R for quick EDA, but ggplot2’s version gives you more control.

ggplot(penguins, aes(x = body_mass_g)) +
  geom_histogram(bins = 20, fill = "steelblue", color = "white")

bins controls how many bars; fill is the color of the bars; color is the outline. Try a few different bins values — the shape of a distribution can look very different with 10 bins vs. 50.

8.7 Customization

8.7.1 Themes

Themes control the overall look — background color, gridlines, font.

ggplot(penguins, aes(x = bill_length_mm, y = bill_depth_mm, color = species)) +
  geom_point() +
  theme_bw()

The themes you’ll use most:

Theme Look
theme_gray() Default — gray panel background
theme_bw() White panel with thin black gridlines
theme_classic() Minimal — just axes, no gridlines
theme_minimal() Light gridlines, no panel border

For class assignments, theme_classic() or theme_bw() look more professional than the default gray.

8.7.2 Facets

A facet splits one plot into a grid of small subplots, one per category. Useful when overlapping points get too crowded.

ggplot(penguins, aes(x = bill_length_mm, y = bill_depth_mm)) +
  geom_point() +
  facet_wrap(~ species)

facet_wrap(~ variable) makes one panel per level of variable. For two grouping variables, use facet_grid(rows ~ cols).

8.7.3 Colors

The default colors are fine, but you can override them. For categorical variables, scale_color_brewer() and scale_fill_brewer() use the ColorBrewer palettes designed for clarity. Dark2 is a good default because it stays distinguishable for colorblind readers; the popular Set1 pairs red with green, which many readers can’t tell apart:

ggplot(penguins, aes(x = bill_length_mm, y = bill_depth_mm, color = species)) +
  geom_point() +
  scale_color_brewer(palette = "Dark2")

For continuous color scales, scale_color_viridis_c() uses the viridis palette, which is colorblind-friendly and prints well in grayscale.

8.8 Saving plots

To save a plot to a file:

my_plot <- ggplot(penguins, aes(x = bill_length_mm, y = bill_depth_mm)) +
             geom_point()

ggsave("scatter.png", plot = my_plot, width = 6, height = 4, dpi = 300)

The file extension sets the format: .png works for most purposes, and .pdf ("scatter.pdf") is better for documents that will be printed. Leave the extension off and ggsave() stops with an error.

8.9 A workflow template

A clean ggplot for a homework write-up usually has these layers, in order:

ggplot(data, aes(x = ..., y = ..., color = ...)) +
  geom_point() +                        # or geom_boxplot, geom_bar, etc.
  labs(title = "...",
       x = "...",
       y = "...",
       color = "...") +
  theme_classic()

Start there, then add facets, color scales, or annotations as the figure demands.