Lesson 8 of 17 · Week 04 · Thu Oct 15
Graphics with ggplot2
Questions
- How do I make a clear, publication-quality plot in R?
Objectives
- Map columns to x, y and colour with
aes(), and draw them with geoms. - Control which layer is drawn on top.
- Tell mapped properties from fixed ones.
- Use log scales, trend lines, facets and labels.
The grammar of graphics
ggplot2 builds a plot from three ingredients: data (a data frame), aesthetic mappings
(which columns go to x, y, colour, size…) and geoms (what shape draws each row: points, lines, boxes). You add
pieces together with +.
library(ggplot2)
ggplot(data = gm, mapping = aes(x = gdpPercap, y = lifeExp)) +
geom_point()
In the exercise boxes, click Run and the plot appears under the output. In Positron it appears in the Plots pane.
Adapted from Software Carpentry's “Creating Publication-Quality Graphics with ggplot2” episode (CC BY 4.0, The Carpentries). Text, examples and exercises have been rewritten for this course.
Lines, groups and layers
ggplot(gm, aes(x = year, y = lifeExp, group = country, colour = continent)) +
geom_line() +
geom_point()
group = country tells geom_line() to draw one line per country instead of zig-zagging through every
point. Layers are drawn in the order you add them: later layers are painted on top of earlier ones.
A mapping inside ggplot() applies to every layer; a mapping inside one geom, e.g.
geom_line(aes(colour = continent)), applies to that layer only.
Mapped vs. fixed properties
Inside aes(), a property depends on the data: aes(colour = continent). Outside
aes(), it's the same for every point: geom_point(colour = "steelblue", size = 3, alpha = 0.6).
Point shapes are numbers (shape = 17 is a filled triangle; see ?points).
Scales and trend lines
ggplot(gm, aes(x = gdpPercap, y = lifeExp)) +
geom_point(alpha = 0.5) +
scale_x_log10() + # GDP spans 500 to 36,000: use a log scale
geom_smooth(method = "lm", se = FALSE) # a straight-line fit (more in Week 05)
If colour = continent is mapped in ggplot(), geom_smooth() fits one line per
continent, because it inherits that grouping.
Facets, labels and themes
ggplot(gm, aes(x = year, y = lifeExp, group = country)) +
geom_line() +
facet_wrap(~ continent) + # one small panel per continent
labs(x = "Year", y = "Life expectancy (years)", title = "Life expectancy, 1967-2007") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45))
facet_grid(rows ~ cols) lays panels out by two variables. theme(axis.text.x = element_blank())
removes the x-axis labels; axis.title.x = element_blank() removes its title.
Exercises
Each exercise gives you up to 10 checked attempts. Use Run as many times as you like to experiment first, then click Check answer when you're ready. Your exercises use numbers/subsets unique to you, so answers won't match a classmate's exactly.
Exercise 1 — GDP over time
0 / 10 attempts usedThis code plots life expectancy against GDP per capita:
ggplot(gm, aes(x = gdpPercap, y = lifeExp)) + geom_point()
Change it so the plot shows how GDP per capita changed over time (time on the x-axis). Store the plot in
p1 and end your code with p1 so it's drawn.
Exercise 2 — Colour by continent
0 / 10 attempts usedStarting from your plot in Exercise 1, colour the points by continent. Store it in
p2. Which continents' GDP grew fastest? Is that what you expected?
Exercise 3 — Which layer is on top?
0 / 10 attempts usedMake p3: life expectancy over time with one line per country coloured by continent,
and points, where the lines are drawn on top of the points. Then swap the layers and compare.
Exercise 4 — Fixed colour and size
0 / 10 attempts usedMake p4: life expectancy against GDP per capita on a log-scaled x-axis, with a straight
trend line (geom_smooth(method = "lm")). Give all the points the colour and size shown when
you click Run. These are fixed values, not mappings.
Exercise 5 — Shapes and one trend per continent
0 / 10 attempts usedMake p5 from the same log-scale scatterplot, but now colour points and trend lines by
continent (so there's one lm line per continent), and draw the points with the shape number shown
when you click Run.
Exercise 6 — Boxplots by continent
0 / 10 attempts usedMake p6: boxplots comparing GDP per capita between continents, using only the rows of
gm from the year shown when you click Run. Label the y-axis
"GDP per capita (USD)". Advanced: remove the x-axis title.
Key Points
- A ggplot = data +
aes()mappings + geoms, added together with+. - Layers are drawn in order: later ones on top.
- Inside
aes()means “depends on the data”; outside means “the same for every point”. - Mappings in
ggplot()are inherited by every layer. - Facets split one plot into small multiples.
Proof of completion
Once you've attempted every exercise above, download a PDF summary of your work on this lesson — your name, the exercises you passed, attempt counts, timing, and your final code for each.