Lesson 8 of 17 · Week 04 · Thu Oct 15

Graphics with ggplot2

Questions

Objectives

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 used

This 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.

Pasting isn't accepted here — please type your answer so it reflects your own work.

      

Exercise 2 — Colour by continent

0 / 10 attempts used

Starting 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?

Pasting isn't accepted here — please type your answer so it reflects your own work.

      

Exercise 3 — Which layer is on top?

0 / 10 attempts used

Make 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.

Pasting isn't accepted here — please type your answer so it reflects your own work.

      

Exercise 4 — Fixed colour and size

0 / 10 attempts used

Make 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.

Pasting isn't accepted here — please type your answer so it reflects your own work.

      

Exercise 5 — Shapes and one trend per continent

0 / 10 attempts used

Make 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.

Pasting isn't accepted here — please type your answer so it reflects your own work.

      

Exercise 6 — Boxplots by continent

0 / 10 attempts used

Make 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.

Pasting isn't accepted here — please type your answer so it reflects your own work.

      

Key Points

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.