8 Plotting with ggplot2
By the end of this chapter you will be able to:
- Build a plot from the grammar of graphics: data, aesthetics, geom layers.
- Create scatterplots, boxplots, bar charts, and histograms.
- Choose between bars and boxplots for group comparisons — and say why.
- Identify misleading-graph features (truncated axes, hidden distributions) using the gallery.
- 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:
- Data — the dataset you’re plotting.
- 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.).
- Geoms — the geometric objects that represent the data (points, lines, bars, boxes).
- 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)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.
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.
8.10 Good, bad, and better: a graph gallery
The best way to develop judgment about visualization is to look at the same data plotted in multiple ways and identify what each version communicates — and obscures. The five examples below each show a problem type, a problematic version, and a better version. R code is provided for both so you can reproduce and modify them.
8.10.1 Example 1 — The truncated y-axis
The problem: Starting the y-axis above zero exaggerates differences visually. A 2.7-point difference in means looks enormous on a scale of 76–83 but small on a scale of 0–100.
library(ggplot2)
means <- data.frame(
group = c("Control", "Treatment"),
score = c(78.5, 81.2)
)
# Bad: truncated y-axis inflates the apparent difference
ggplot(means, aes(x = group, y = score, fill = group)) +
geom_col(width = 0.5) +
coord_cartesian(ylim = c(76, 83)) +
labs(title = "Misleading: truncated y-axis",
y = "Mean score", x = NULL) +
theme_minimal() +
theme(legend.position = "none")
# Better: y-axis starts at 0
ggplot(means, aes(x = group, y = score, fill = group)) +
geom_col(width = 0.5) +
coord_cartesian(ylim = c(0, 100)) +
labs(title = "Better: full scale from 0",
y = "Mean score", x = NULL) +
theme_minimal() +
theme(legend.position = "none")Rule: For bar charts (which encode quantity as area from a zero baseline), always start the y-axis at zero. For dot plots and line charts — which encode change or difference, not absolute quantity — truncating the axis is sometimes appropriate and should be disclosed.
8.10.2 Example 2 — Bar chart vs. violin/jitter
The problem: Bar charts of group means hide the distribution. Two groups can have identical means and standard deviations but very different underlying distributions (bimodal, skewed, one outlier driving the mean).
set.seed(42)
df <- data.frame(
group = rep(c("A", "B"), each = 30),
score = c(rnorm(30, mean = 65, sd = 12),
c(rnorm(15, 55, 5), rnorm(15, 75, 5))) # bimodal B
)
# Bad: bar chart hides distribution shape
ggplot(df, aes(x = group, y = score, fill = group)) +
stat_summary(fun = mean, geom = "bar", width = 0.5) +
stat_summary(fun.data = mean_se, geom = "errorbar", width = 0.2) +
labs(title = "Misleading: bar chart hides bimodal B",
y = "Score") +
theme_minimal() + theme(legend.position = "none")
# Better: violin + jitter shows the real shape
ggplot(df, aes(x = group, y = score, fill = group)) +
geom_violin(alpha = 0.4) +
geom_jitter(width = 0.1, alpha = 0.5, size = 1.5) +
stat_summary(fun = mean, geom = "point",
shape = 18, size = 4, color = "black") +
labs(title = "Better: violin + jitter reveals bimodal B",
y = "Score") +
theme_minimal() + theme(legend.position = "none")Rule: For group comparisons with continuous outcomes, prefer violin plots, jitter plots, or boxplots over bar charts. If you must use a bar chart, include individual data points whenever n is small enough to plot.
8.10.3 Example 3 — Pie chart vs. bar chart for categorical proportions
The problem: Humans are poor at comparing areas and angles in pie charts. Comparing bar heights is much more accurate.
survey <- data.frame(
response = c("Strongly agree", "Agree", "Neutral",
"Disagree", "Strongly disagree"),
pct = c(12, 34, 28, 18, 8)
)
# Bad: pie chart — hard to compare non-adjacent slices
ggplot(survey, aes(x = "", y = pct, fill = response)) +
geom_col() +
coord_polar("y") +
labs(title = "Harder to read: pie chart for proportions",
fill = "Response") +
theme_void()
# Better: horizontal bar chart — easier to rank and compare
survey$response <- factor(survey$response,
levels = rev(c("Strongly agree", "Agree", "Neutral",
"Disagree", "Strongly disagree")))
ggplot(survey, aes(x = pct, y = response, fill = response)) +
geom_col(width = 0.6) +
labs(title = "Better: bar chart for proportions",
x = "Percent (%)", y = NULL) +
theme_minimal() + theme(legend.position = "none")Rule: Use bar charts, not pie charts, whenever comparing more than 2–3 categories. Exception: a two-category pie (50/50 or 75/25) is readable, but a bar chart is still more precise.
8.10.4 Example 4 — Overplotting with many points
The problem: When many points share similar values, they stack on top of each other and the plot looks like far fewer points are present than actually exist. This hides the density of the data.
set.seed(7)
big_df <- data.frame(
x = round(rnorm(500, mean = 5, sd = 1)),
y = round(rnorm(500, mean = 5, sd = 1))
)
# Bad: solid points, all stacked
ggplot(big_df, aes(x = x, y = y)) +
geom_point(size = 2) +
labs(title = "Misleading: overplotting hides density") +
theme_minimal()
# Better option 1: transparency
ggplot(big_df, aes(x = x, y = y)) +
geom_point(size = 2, alpha = 0.15) +
labs(title = "Better: alpha transparency shows density") +
theme_minimal()
# Better option 2: jitter + alpha (for integer-valued data)
ggplot(big_df, aes(x = x, y = y)) +
geom_jitter(width = 0.3, height = 0.3, alpha = 0.2, size = 1.5) +
labs(title = "Better: jitter + alpha for discrete grid") +
theme_minimal()Rule: With more than ~100 points, use alpha (transparency), geom_jitter(), geom_hex() (needs install.packages("hexbin") first), or geom_density_2d() to reveal density structure that solid points hide.
8.10.5 Example 5 — Wrong chart type for the data level
The problem: Using a line graph to connect group means implies a meaningful ordered sequence between groups. If groups are nominal categories (no natural order), the line is misleading — it implies a trend where none exists.
diets <- data.frame(
diet = c("Mediterranean", "Vegan", "Paleo", "Standard"),
cholesterol = c(178, 165, 184, 195)
)
# Bad: line chart implies ordered trend across nominal groups
ggplot(diets, aes(x = diet, y = cholesterol, group = 1)) +
geom_line(color = "steelblue", linewidth = 1) +
geom_point(size = 3) +
labs(title = "Misleading: line chart for nominal groups",
x = "Diet", y = "Mean cholesterol (mg/dL)") +
theme_minimal()
# Better: dot plot (Cleveland dot plot) — no implied continuity
ggplot(diets, aes(x = cholesterol,
y = reorder(diet, -cholesterol))) +
geom_point(size = 4, color = "steelblue") +
labs(title = "Better: dot plot for unordered groups",
x = "Mean cholesterol (mg/dL)", y = "Diet") +
theme_minimal()Rule: Reserve line charts for data with a natural ordering on the x-axis — time series, ordered conditions (low/medium/high), or continuous predictors. For unordered nominal categories, use bar charts, dot plots, or boxplots.
The next chapter covers reshaping data — the manipulation step you’ll need before plotting or analyzing any repeated-measures dataset.
Core idea: Every ggplot is the same sentence — data + aesthetics + geoms, combined with +. Aesthetics map variables to visual properties; geoms draw them; faceting and themes refine the result.
You should understand:
- The grammar of graphics: data, aesthetics, geoms, and optional layers
- Why bar charts of means hide the distribution that boxplots and jittered points reveal
- The misleading-graph patterns from the gallery: truncated axes, wrong chart for the variable type, overplotting
You should be able to do in R:
- Build a scatterplot, boxplot, bar chart, and histogram with
ggplot() - Facet a plot by a grouping variable with
facet_wrap() - Save a plot with
ggsave()
Plain-language check: A figure shows two bars that look dramatically different, one about twice as tall as the other, but the y-axis runs from 49 to 51. What is the figure doing, and how would you redraw it honestly?
The one mistake to avoid: Reporting a bar chart of group means when the question is about distributions. Bars show one number per group; boxplots and violin plots show what the data actually look like.
Practice: Using the babies data, make a boxplot of birth weight by smoking group, then add jittered points on top. What do the points show that the boxes alone don’t? Start from the Chapter 7 template, so smoke_bi is a factor (as a number, you’d get one box instead of two). Then drop the mothers smoke_bi leaves out, or they’ll appear as a third box labeled NA: ggplot(subset(babies, !is.na(smoke_bi)), aes(x = smoke_bi, y = bwt)).
Key terms from this chapter are defined in the Glossary.