MY202 · Lab 2
Jonas Weinert
Department of Methodology | London School of Economics and Political Science
29 October 2026
| 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.
Warm-up
Two questions · choosing a chart · saying what it shows
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?
Two captions for the same histogram. Which one helps a reader more?
ANNOTATION HERE.Part 1
Five packages · 301 school children · 26 mental ability tests
Notebook lines 16–36 the library chunk, then hs_datarun together
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.
t01_visperc to t26_flags: spatial, verbal, speed, memory, reasoningnuijten2020: 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.
Part 2.0
Data · aesthetics · geometry · then the look
Notebook lines 58–64 the first scatter plotrun together
hs_data |> ggplot(aes(t08_wordclas, t09_wordmean)) + geom_point()
colour = and fill =.+, not |>.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.
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 lookNotebook 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()
theme() sets one plot part per line: name of the part = what to do.element_blank() removes a part: here the grid lines, then the ticks.element_rect() restyles a box: here a see-through background.+. Result: next slide.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
Notebook line 133 every exercise chunk starts with thislook
#| fig-cap: "**Figure 1:** Most students score …"
**…** 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?
Today’s six exercises, drawn from the lab’s data. Start from the question, then pick the chart.
Parts 2.1–2.2
Histograms and bar charts · one number, and counts per group
2.1 and 2.2 · lines 130–152
t02_cubesschool, then a bar chart of the countslabs()ANNOTATION HERE with what the plot showsSyntax 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 nStuck?
stat_bin() using bins = 30: a message, not an error. Set bins = yourself+geom_bar() counts for you, so you can skip count()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).
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).
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.
Parts 2.3–2.4
Scatter plots and line plots · two numbers, and change over time
2.3 and 2.4 · lines 160–182
t01_visperc against t03_frmbord, coloured by schoolnuijten2020 by year, then a line (or area) plotgeom_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?
colour = school goes inside aes(). Outside it means “paint everything this colour”theme(legend.position = "bottom")scale_colour_*() for points and lines, scale_fill_*() for bars and areastheme_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).
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.
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.
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.
Parts 2.5–2.6
Box plots and density plots · comparing groups
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.
2.5 and 2.6 · lines 191–213
t16_figrrecg by grade. Line 191 says “histogram”: it means box plott23_series by gender (female: 1 = male, 2 = female)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 titleStuck?
grade in as.factor()alpha== compares, = names an argument (Lab 1)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.
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).
Universal design
Five principles · colour for everyone · a makeover
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.
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().
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.
Pairs · any plot from today
Checklist
+. A column that should change the picture goes inside aes(); a fixed colour goes outsideas.factor() on purposeQuestion: pick your best plot from today. What would a reader learn from its caption alone?
Week 3 Linear regression, our first algorithm
How was today’s lab? Scan the code, or open forms.gle/i3uobCAaGmkzf1ns7. It takes 30 seconds and changes what next week looks like.
MY202 · Lab 2 · Data visualisation