Data visualisation: building plots with ggplot

MY202 · Lab 2

Jonas Weinert

Department of Methodology  |  London School of Economics and Political Science

29 October 2026

Lab overview

Part Topic Functions Mode Time
Setup, two warm-up questions, meet the data library(), as_tibble() together 8 min
2.0 How a ggplot is built, and themes ggplot(), aes(), geom_point(), theme() together 14 min
2.1–2.2 Distributions and counts geom_histogram(), count(), geom_col() your turn 15 min
2.3–2.4 Relationships and time geom_jitter(), scale_colour_*(), geom_line() your turn 18 min
2.5–2.6 Comparing groups geom_boxplot(), geom_density(), if_else() concept, then your turn 16 min
Design principles, peer critique, wrap-up together · pairs 14 min

Together: we type the code into the notebook, the slide explains each piece, and the line number says where. Your turn: a timer, tasks and an annotated syntax sheet, then the solutions step by step.

Visualisation

Warm-up

Two questions · choosing a chart · saying what it shows

Warm-up 1 of 2

Warm-up1 · Setup2.0 · ggplot2.1–2.22.3–2.42.5–2.6DesignWrap-up

You have one test score for each of 300 students. You want to show how the scores are spread out: are most in the middle, are there a few very low ones? Which chart?

AA bar chart with one bar per student
BA histogram: bars that count how many students fall in each score range
CA line plot of the scores in the order of the data
DA pie chart
B. A histogram groups the scores into ranges (bins) and counts each. 300 bars (A) is unreadable, and the order of the rows (C) means nothing. That's exercise 2.1.

Warm-up 2 of 2

Warm-up1 · Setup2.0 · ggplot2.1–2.22.3–2.42.5–2.6DesignWrap-up

Two captions for the same histogram. Which one helps a reader more?

A“Figure 1: Histogram of t02_cubes.”
B“Figure 1: Most students score between 5 and 7 on the cubes test.”
CNo caption: the plot speaks for itself
B. A says what the plot is; the reader can see that. B says what it shows. Every exercise today ends with a caption like B: the notebook's ANNOTATION HERE.

Setup

Part 1

Five packages · 301 school children · 26 mental ability tests

Setup

Warm-up1 · Setup2.0 · ggplot2.1–2.22.3–2.42.5–2.6DesignWrap-up

Notebook lines 16–36 the library chunk, then hs_datarun together

library("ggsci")       # colour palettes
library("ggthemes")    # more ready-made themes
library("psychTools")  # the Holzinger-Swineford data
library("psymetadata") # the Nuijten (2020) data
library("tidyverse")   # dplyr, ggplot2 and friends

hs_data <-
  holzinger.swineford |>
  as_tibble()

hs_data

No data files today Both data sets come inside R packages. Loading the package is enough; as_tibble() makes it print nicely, as in Lab 1.

What’s in it? ?holzinger.swineford in the console opens the help page with every column (line 38).

ggplot2 is already loaded It’s one of the packages inside tidyverse.

Meet the data

Warm-up1 · Setup2.0 · ggplot2.1–2.22.3–2.42.5–2.6DesignWrap-up
301children in grades 7 and 8 at two US schools, tested in the late 1930s. One row each.
26mental ability tests, t01_visperc to t26_flags: spatial, verbal, speed, memory, reasoning
2,443rows in the second data set, nuijten2020: results from 131 reviews of intelligence research. Used in 2.4.

Who they are school (Pasteur 156, Grant-White 145) · grade (7 or 8) · female · ageyr

Tests used today t01_visperc visual perception · t02_cubes · t03_frmbord form board · t08_wordclas · t09_wordmean · t16_figrrecg figure recognition · t23_series

Watch the coding female is 1 for male and 2 for female, not 0/1. grade is stored as a number. Both matter in 2.5 and 2.6.

How a ggplot is built

Part 2.0

Data · aesthetics · geometry · then the look

Every ggplot has three parts

Warm-up1 · Setup2.0 · ggplot2.1–2.22.3–2.42.5–2.6DesignWrap-up

Notebook lines 58–64 the first scatter plotrun together

hs_data |> ggplot(aes(t08_wordclas, t09_wordmean)) + geom_point()

  1. Data. Which table to plot. Piped in, as in Lab 1.
  2. Start a plot. An empty canvas for that data.
  3. Aesthetics: which column goes where. The first is the x axis, the second the y axis. Later also colour = and fill =.
  4. Add a layer. Plots are built by adding pieces with +, not |>.
  5. Geometry: how to draw each row. geom_point() draws a dot; geom_histogram(), geom_col(), geom_line() draw other shapes.

In words: take hs_data, put word classification on x and word meaning on y, and draw a dot for each student.

A plot, one layer at a time

hs_data |>
  ggplot(aes(t08_wordclas, t09_wordmean)) +
  geom_point() +
  labs(x = "Word classification",
       y = "Word meaning") +
  theme_minimal()

Each click adds one line, and one thing to the picture. Lines 1–3 are the notebook’s; the last two are where today’s exercises go further.

ggplot() and aes() alone: the axes are set up from the data, but nothing is drawn yet.

geom_point(): one dot per student. Students who do well on one test tend to do well on the other.

labs() replaces column names with words a reader understands.

A theme changes the look, never the data: here the grey background goes.

theme(): change the look

Warm-up1 · Setup2.0 · ggplot2.1–2.22.3–2.42.5–2.6DesignWrap-up

Notebook lines 68–98 theme(), then my_theme()run together

my_theme <- function() { theme( panel.grid = element_blank(), axis.ticks = element_blank(), panel.background = element_rect(fill = "transparent") ) } hs_data |> ggplot(…) + geom_point() + my_theme()

  1. Save the style under a name. A function with no inputs, so you can reuse it.
  2. theme() sets one plot part per line: name of the part = what to do.
  3. element_blank() removes a part: here the grid lines, then the ticks.
  4. element_rect() restyles a box: here a see-through background.
  5. Use it like any layer, with +. Result: next slide.

Four looks, same plot

Warm-up1 · Setup2.0 · ggplot2.1–2.22.3–2.42.5–2.6DesignWrap-up

Notebook lines 102–122 theme_minimal(), ggthemes::theme_clean(), and links for morerun together

Start from a ready-made theme, then adjust Every solution today does this: theme_minimal() + theme(panel.grid.minor = element_blank()). The full theme first, your changes after.

Today’s three-part recipe 1 a theme function · 2 the skeleton plot · 3 the annotation: a caption that says what the plot shows

The annotation: a caption that says the finding

Warm-up1 · Setup2.0 · ggplot2.1–2.22.3–2.42.5–2.6DesignWrap-up

Notebook line 133 every exercise chunk starts with thislook

#| fig-cap: "ANNOTATION HERE"

# Code here

#| fig-cap: "**Figure 1:** Most students score …"

  1. A chunk option, read by Quarto when it renders, not by R. Must be the first lines of the chunk.
  2. The caption printed under the figure.
  3. Your sentence. **…** makes bold text.

Describes the plot “Histogram of cube test scores.” The reader can see that.

Says what it shows “Most students score between 5 and 7 on the cubes test.” That’s the finding.

Test your caption Cover the plot. Does the caption alone tell someone what you found?

Which chart for which question?

Warm-up1 · Setup2.0 · ggplot2.1–2.22.3–2.42.5–2.6DesignWrap-up

Today’s six exercises, drawn from the lab’s data. Start from the question, then pick the chart.

Round 1

Parts 2.1–2.2

Histograms and bar charts · one number, and counts per group

Exercises: 2.1 and 2.2

2.1 and 2.2 · lines 130–152

  1. Line 132, 2.1: a histogram of t02_cubes
  2. Line 147, 2.2: count the students in each school, then a bar chart of the counts
  3. Each plot: a theme function, readable axis labels with labs()
  4. Replace ANNOTATION HERE with what the plot shows

Syntax you need

theme_histogram <- function() {
  theme_minimal() +                 # start from a theme
    theme(panel.grid.minor = element_blank())  # then adjust
}

hs_data |>
  ggplot(aes(t02_cubes)) +          # one column: x only
  geom_histogram(bins = 20,         # how many bars
                 colour = "black",  # outline of the bars
                 fill = "lightgrey") +   # inside of the bars
  theme_histogram() +
  labs(x = "Cube test scores", y = "Count")

hs_data |>
  count(school) |>                  # a table: school, n
  ggplot(aes(n, school)) +          # n on x, school on y
  geom_col()                        # one bar per row, length n

Stuck?

  • stat_bin() using bins = 30: a message, not an error. Set bins = yourself
  • Can’t find the plot: every line except the last needs a +
  • geom_bar() counts for you, so you can skip count()

Solutions: 2.1 histogram

theme_histogram <- function() {
  theme_minimal() +
    theme(
      panel.grid.minor = element_blank(),
      panel.grid.major.x = element_blank()
    )
}

hs_data |>
  ggplot(aes(t02_cubes)) +
  geom_histogram(
    bins = 20,
    colour = "black",
    fill = "lightgrey",
    alpha = 0.5
  ) +
  theme_histogram() +
  labs(x = "Cube test scores", y = "Count")

The recipe: a theme function, the skeleton, the labels. Then the caption.

Nothing is drawn yet: this stores a look under a name. Minor grid lines and the vertical grid lines go; bars don’t need them.

The default histogram, with 20 bins, black outlines and a light fill. alpha = 0.5 makes the fill half see-through.

Theme and labels on. Caption: Most students score between 5 and 7 on the cubes test (72% do).

Solutions: 2.2 bar chart

theme_bar <- function() {
  theme_minimal() +
    theme(
      panel.grid.minor = element_blank(),
      panel.grid.major.y = element_blank()
    )
}

hs_data |>
  count(school) |>
  ggplot(aes(n, school)) +
  geom_col() +
  theme_bar() +
  labs(x = "Number of students", y = "School")

First summarise with count(), then plot the summary.

count() from Lab 1: a two-row table. This is what gets plotted, not the 301 students.

# A tibble: 2 × 2
  school          n
  <chr>       <int>
1 Grant-White   145
2 Pasteur       156

n on x and school on y: the bars lie down, so the names are easy to read. geom_col() draws each bar as long as n.

The horizontal grid lines go (they’d run through the bars). Caption: There are slightly more students from Pasteur (156) than from Grant-White (145).

Round 1: bins are a design choice

Warm-up1 · Setup2.0 · ggplot2.1–2.22.3–2.42.5–2.6DesignWrap-up

Too few Everything in a few blocks: the shape disappears.

About right The shape is clear: a peak around 6, a longer tail to the right.

Too many Gaps and spikes: the test scores in quarter points show through, not the shape.

Round 2

Parts 2.3–2.4

Scatter plots and line plots · two numbers, and change over time

Exercises: 2.3 and 2.4

2.3 and 2.4 · lines 160–182

  1. Line 162, 2.3: t01_visperc against t03_frmbord, coloured by school
  2. Line 177, 2.4: count the rows of nuijten2020 by year, then a line (or area) plot
  3. Theme, labels, caption for each
  4. Fast? Try geom_jitter() instead of geom_point() in 2.3. What changes?

Syntax you need

hs_data |>
  ggplot(aes(t01_visperc, t03_frmbord,
             colour = school)) +  # a column → a colour
  geom_point(alpha = 0.5,         # half see-through
             size = 2) +
  scale_colour_cosmic() +         # a ggsci palette
  labs(x = "Visual perception", y = "Form board",
       colour = "School")         # the legend's title

nuijten2020 |>
  as_tibble() |>
  count(year) |>                  # a table: year, n
  ggplot(aes(year, n)) +
  geom_line(colour = "midnightblue")  # or geom_area()

Stuck?

  • All dots one colour: colour = school goes inside aes(). Outside it means “paint everything this colour”
  • Legend at the side: theme(legend.position = "bottom")
  • scale_colour_*() for points and lines, scale_fill_*() for bars and areas

Solutions: 2.3 scatter plot

theme_scatter <- function() {
  theme_minimal() +
    theme(panel.grid.minor = element_blank(),
          legend.position = "bottom")
}

hs_data |>
  ggplot(aes(t01_visperc, t03_frmbord,
             colour = school)) +
  geom_jitter(alpha = 0.5, size = 2) +
  theme_scatter() +
  scale_colour_cosmic() +
  labs(x = "Visual Perception", y = "Form Board",
       colour = "School")

colour = school inside aes(): one colour per school, and a legend for free.

Default colours. geom_jitter() moves each dot a tiny random amount: next slide.

The theme moves the legend under the plot; scale_colour_cosmic() swaps the colours for a ggsci palette.

Caption: In both schools, students who score higher on visual perception tend to score higher on the form board (correlation 0.37).

Hidden dots: overplotting

Warm-up1 · Setup2.0 · ggplot2.1–2.22.3–2.42.5–2.6DesignWrap-up

Why? The tests are scored in steps, so 301 students share only 177 positions. With geom_point(), students with the same scores sit exactly on top of each other.

Two fixes, used together geom_jitter() nudges each dot a little; alpha = 0.5 makes dots see-through, so a stack looks darker.

Solutions: 2.4 line plot

theme_line <- function() {
  theme_minimal() +
    theme(
      panel.grid.minor = element_blank(),
      panel.grid.major.x = element_blank()
    )
}

nuijten2020 |>
  as_tibble() |>
  count(year) |>
  ggplot(aes(year, n)) +
  geom_line(colour = "midnightblue") +
  theme_line() +
  labs(x = "Year",
       y = "Number of Studies in Nuijten (2020)")

colour = "midnightblue" is outside aes(): one fixed colour, no legend.

One row per year that appears in the data, 1915 to 2013, and how many rows have that year.

# A tibble: 77 × 2
   year     n
  <int> <int>
1  1915     1
2  1928     2
3  1931     1
4  1934     3
# ℹ 73 more rows

geom_line() joins the years in order. A peak in 2005 (126), then a steep drop.

Caption: Most of the results in Nuijten (2020) come from studies published in the 1990s and 2000s. But is “studies” right? Next slide.

Round 2: what is one row?

Warm-up1 · Setup2.0 · ggplot2.1–2.22.3–2.42.5–2.6DesignWrap-up

count() counts rows One row of nuijten2020 is one effect size, a single result. 2,443 results come from 1,917 studies: some report several. The y label should say “results”, not “studies”.

Why does the line drop after 2008?

Not less research The data come from reviews finished by about 2014. Recent studies hadn’t been picked up yet. The drop is about how the data were collected, not about the world.

Round 3

Parts 2.5–2.6

Box plots and density plots · comparing groups

Reading a box plot

Warm-up1 · Setup2.0 · ggplot2.1–2.22.3–2.42.5–2.6DesignWrap-up

The 144 grade 8 students’ figure recognition scores (t16_figrrecg), one dot each.

The box The middle half of the students. The line inside is the median.

Why use it Five numbers instead of 144 dots, so several groups fit side by side: middle, spread, and unusual values.

Exercises: 2.5 and 2.6

2.5 and 2.6 · lines 191–213

  1. Line 193, 2.5: box plots of t16_figrrecg by grade. Line 191 says “histogram”: it means box plot
  2. Line 208, 2.6: density plots of t23_series by gender (female: 1 = male, 2 = female)
  3. Theme, labels, caption for each

Syntax you need

hs_data |>
  ggplot(aes(as.factor(grade),       # 7 and 8 as groups,
             t16_figrrecg)) +        #   not as numbers
  geom_boxplot()

hs_data |>
  mutate(gender = if_else(female == 2,     # test
                          "Female",        # if TRUE
                          "Male")) |>      # if FALSE
  ggplot(aes(t23_series, fill = gender)) + # fill by group
  geom_density(alpha = 0.3) +              # see-through
  scale_fill_lancet() +
  labs(fill = NULL)                        # no legend title

Stuck?

  • One box only and a warning about continuous x: wrap grade in as.factor()
  • Curves solid, one hides the other: lower alpha
  • == compares, = names an argument (Lab 1)

Solutions: 2.5 box plot

theme_boxplot <- function() {
  theme_minimal() +
    theme(panel.grid = element_blank(),
          legend.position = "none")
}

hs_data |>
  ggplot(aes(as.factor(grade), t16_figrrecg)) +
  geom_boxplot(alpha = 0.75) +
  theme_boxplot() +
  scale_fill_bmj() +
  labs(x = "Grade",
       y = "Figure Recognition Scores")

as.factor(grade) turns the numbers 7 and 8 into two groups.

One box per grade. The dot near the bottom is an outlier.

Caption: Figure recognition scores are slightly higher in grade 8 (median 6.86) than in grade 7 (6.57). scale_fill_bmj() does nothing here: no fill = in aes().

Without as.factor(): ggplot sees one continuous x, draws one box for everyone, and warns Continuous x aesthetic.

Solutions: 2.6 density plot

theme_density <- function() {
  theme_minimal() +
    theme(panel.grid = element_blank(),
          legend.position = "bottom")
}

hs_data |>
  mutate(gender = if_else(female == 2,
                          "Female", "Male")) |>
  ggplot(aes(t23_series, fill = gender)) +
  geom_density(alpha = 0.325) +
  theme_density() +
  scale_fill_lancet() +
  labs(x = "Series Completion Scores",
       y = "Density", fill = NULL)

A new column with words, then fill = that column.

if_else(): 2 becomes “Female”, everything else “Male”.

# A tibble: 301 × 3
  female gender t23_series
   <dbl> <chr>       <dbl>
1      1 Male        0.556
2      2 Female      0.111
3      2 Female      0.778
4      1 Male        0.667
# ℹ 297 more rows

A smooth version of a histogram per group. alpha lets you see both curves where they overlap.

Caption: Boys and girls have almost the same series completion scores (means 2.08 and 1.96).

Design principles

Universal design

Five principles · colour for everyone · a makeover

Five principles for any chart

Warm-up1 · Setup2.0 · ggplot2.1–2.22.3–2.42.5–2.6DesignWrap-up

Notebook lines 215–229 Universal Design Principlesread

Accessibility Works for colour-blind readers and in black and white. Use shape or position as well as colour.

Clarity Every element earns its place. Gridlines, legends, colours you don’t need: remove them.

Context Enough to understand it alone: axis labels in words, units, a caption, the source.

Consistency Same scales, colours and style across related plots. Your theme functions do this.

Focus Point the reader to the finding: colour or size for what matters, grey for the rest.

The goal Understanding, not showing off. Clarity over complexity.

Accessibility: colour for everyone

Warm-up1 · Setup2.0 · ggplot2.1–2.22.3–2.42.5–2.6DesignWrap-up

About 1 in 12 men and 1 in 200 women have a red–green colour vision deficiency. The middle plot is a simulation: the two schools become one.

Two fixes A colour-blind safe palette (scale_colour_viridis_d(), or Okabe–Ito with scale_colour_manual()), and a second cue: shape = school inside aes().

Makeover: same data, a clear message

Warm-up1 · Setup2.0 · ggplot2.1–2.22.3–2.42.5–2.6DesignWrap-up

Context Axis labels in words; the finding as the title.

Clarity Grey background and grid lines gone.

Focus The group the title talks about is in colour; the other is grey.

Peer critique

Pairs · any plot from today

  1. Swap screens with your neighbour. Pick one of their six plots
  2. Cover the plot: does the caption alone say what they found?
  3. Check it against the five principles. Name one thing to change
  4. Make the change in your own plot. Rewrite your caption if needed

Checklist

1Accessibility: would it work in black and white?
2Clarity: anything there for no reason?
3Context: labels in words, not column names?
4Consistency: same style as their other plots?
5Focus: is the eye drawn to the finding?

Summary

Warm-up1 · Setup2.0 · ggplot2.1–2.22.3–2.42.5–2.6DesignWrap-up
1Every ggplot is data + aesthetics + a geom, joined with +. A column that should change the picture goes inside aes(); a fixed colour goes outside
2Start from the question to pick the chart: spread (histogram), counts (bar), two numbers (scatter), time (line), groups (box, density). Then check what one row is, and choose bins, jitter and as.factor() on purpose
3The recipe: a theme function, the skeleton, and a caption that says the finding. Design for everyone: colour-blind safe, clear, in context, consistent, focused

Question: pick your best plot from today. What would a reader learn from its caption alone?

Further reading

Week 3 Linear regression, our first algorithm

30 seconds of feedback

QR code linking to the feedback survey

How was today’s lab? Scan the code, or open forms.gle/i3uobCAaGmkzf1ns7. It takes 30 seconds and changes what next week looks like.