Data visualisation: building plots with ggplot
MY202 · Lab 2 · Self-paced guide
Before you start
This page walks you through Lab 2 one small step at a time. It assumes you have done Lab 1, so you know what a notebook, a chunk, a pipe |>, count(), mutate() and group_by() are. ggplot is new: everything about it is explained the first time it appears, and there is a glossary at the end.
What’s new this week. Last week you summarised and reshaped data. This week you draw it, with ggplot2, the plotting part of the tidyverse. You’ll make six kinds of chart. For each one, the notebook asks for the same three things: a theme (the look), the plot itself, and an annotation: one sentence that says what the plot shows. The last part matters as much as the code. A chart is only useful if a reader can tell what you found.
Your turn Something to do in the notebook. The box says which notebook lines to go to.
What you should see The real result R gives back. Compare it with yours.
Big idea A concept worth remembering beyond today.
Check yourself A quick question. Click an answer to see if you were right.
At the end of each step there is a Mark as done button. Your ticks are saved in this browser, so you can close the page and pick up where you left off.
The student notebook has an empty # Code here chunk for each of the six exercises. Try each one first; the code is in a “Show the code” box underneath if you get stuck. Your plot doesn’t have to look exactly like the one shown: colours and themes are your choice.
Setup and the data take about 15 minutes, how a ggplot is built 30, the six exercises about an hour, and the design principles 15.
Open the notebook and run the setup chunks
- Open the Lab 2 student notebook on Nuvolos. The packages are already installed there.
- Run the chunk at lines 16–23. It loads five packages.
- Run the chunk at lines 29–36. It creates an object called
hs_dataand prints it.
| Package | What it gives you |
|---|---|
tidyverse |
dplyr from Lab 1, and ggplot2, today’s plotting package. Loading tidyverse loads both. |
ggthemes |
More ready-made themes, such as theme_clean(). |
ggsci |
Colour palettes from scientific journals and TV shows: scale_colour_cosmic(), scale_fill_lancet()… |
psychTools |
Contains the Holzinger-Swineford data, used in five of the six exercises. |
psymetadata |
Contains the Nuijten (2020) data, used in exercise 2.4. You met this package in Lab 1. |
Right: both data sets come inside R packages. Once psychTools is loaded, an object called holzinger.swineford simply exists. The chunk at line 29 only turns it into a tibble with as_tibble(), so it prints neatly, and saves it as hs_data.
Part 1: Meet the data
The Holzinger-Swineford data
hs_data has one row per child: 301 children in grades 7 and 8 at two US schools, who sat 26 mental ability tests in the late 1930s. It’s a classic data set in psychology.
| Column | What it is |
|---|---|
school |
Pasteur (156 children) or Grant-White (145) |
grade |
7 or 8. Stored as a number |
female |
1 = male, 2 = female. Not 0/1! |
ageyr, mo, agemo |
Age in years, extra months, and age in months |
t01_visperc … t26_flags |
One score per test. Today: t01_visperc (visual perception), t02_cubes (spatial cubes), t03_frmbord (form board: fitting shapes together), t08_wordclas (word classification), t09_wordmean (word meaning), t16_figrrecg (figure recognition: remembering shapes), t23_series (completing number series) |
Type ?holzinger.swineford in the console (the bottom-left pane in RStudio) and press Enter. The help page lists every column. This works for any data set that comes with a package, for example ?nuijten2020.
The Nuijten (2020) data
Exercise 2.4 uses a second data set, nuijten2020. Nuijten and colleagues collected the results of 131 published reviews of intelligence research. Each review summarised many primary studies, and each row of nuijten2020 is one result from one of those studies: 2,443 rows. The column you need is year, the year the primary study came out.
Before you plot, ask: what is one row? In hs_data, one row is one child. In nuijten2020, one row is one result, and one study can report several. That difference comes back in exercise 2.4.
Part 2.0: How a ggplot is built
About 30 minutes. Everything in this part is already written in the notebook (lines 54–122): you run it and understand it. The exercises after it are where you write your own.
The three parts of every ggplot
Run the first plot chunk.
hs_data |> ggplot(aes(t08_wordclas, t09_wordmean)) + geom_point()
- Data. Which table to plot, piped in as in Lab 1.
- Start a plot.
ggplot()makes an empty canvas for that data. - Aesthetics: which column goes where. Inside
aes(), the first column goes on the x axis (across), the second on the y axis (up). Later you’ll also seecolour =andfill =in here. - Add a layer. A plot is built by adding pieces with
+. Not|>: the pipe hands data to a function;+adds something to a plot. - Geometry: how to draw each row.
geom_point()draws a dot for each child. Swap it for anothergeom_and the same data become a different chart.
In words: take hs_data, put word classification on x and word meaning on y, and draw a dot for each child. Children who do well on one word test tend to do well on the other.
Every ggplot is data + aesthetics + a geom, joined with +. This is called the grammar of graphics: instead of choosing from a menu of chart types, you say which column goes where and which shape to draw.
Error: `mapping` must be created by `aes()`
Did you use `%>%` or `|>` instead of `+`?
You wrote |> after ggplot(...). Use + from ggplot() onwards. A related problem: if a + is missing at the end of a line, R stops there and the layers below it are never added (or you get an error on the next line).
Building a plot one layer at a time
Each layer you add changes one thing in the picture. Step through the code: every step highlights the line it adds.
hs_data |>
ggplot(aes(t08_wordclas, t09_wordmean)) +
geom_point() +
labs(x = "Word classification",
y = "Word meaning") +
theme_minimal()ggplot() and aes() alone: the axes are set up from the data, but nothing is drawn, because there’s no geom yet.
geom_point(): one dot per child.
labs() replaces the column names on the axes with words a reader understands.
A theme changes the look, never the data. theme_minimal() removes the grey background.
Changing the look with theme()
Run the chunk at lines 68–79, then the one at lines 83–98.
theme() controls every part of a plot that isn’t data: background, grid lines, axis ticks, fonts, where the legend goes. Each line inside it names one part and says what to do with it. The second chunk saves the same style under a name, so you can reuse it:
my_theme <- function() { theme(panel.grid = element_blank(), axis.ticks = element_blank(), panel.background = element_rect(fill = "transparent")) }
- Save the style under a name.
function() { … }makes a function with no inputs. Callingmy_theme()later runs what’s inside. - One plot part per line, written as name of the part
=what to do. element_blank()removes a part. Here the grid lines; then the axis ticks.element_rect()restyles a rectangle. Here the background becomes see-through.
Why a function? You’ll style six plots today. Write the look once, use it everywhere, and all your plots match.
Nobody remembers them all. Type theme( in RStudio and press Tab to see the list, or ask an LLM in plain words: “in ggplot, how do I remove the vertical grid lines?” (answer: panel.grid.major.x = element_blank()). The notebook’s hot take (line 52) is exactly this: let AI help with the syntax, and spend your own time on what the plot should say.
Ready-made themes
Run the theme_minimal() chunk and the ggthemes::theme_clean() chunk.
Same data, same points, four looks. ggthemes:: in front of a function says which package it comes from; it isn’t needed once the package is loaded, but it helps the reader. For fun, lines 118–122 link to more theme packages. (The ggpomological link points to the tvthemes page by mistake; ggpomological is at github.com/gadenbuie/ggpomological.)
Start from a ready-made theme, then adjust. Every solution today writes its theme function the same way: theme_minimal() + theme(…your changes…). The full theme comes first because it resets everything; your changes come after and win.
You write theme(panel.grid = element_blank()) + theme_minimal(). What happens to the grid lines?
They’re removed
Not quite. theme_minimal() comes last and sets the whole look again, grid lines included.
They come back
Yes. The later theme overwrites the earlier one. Put the ready-made theme first and your changes after it.
R gives an error
No error: both are valid layers. The order decides which one wins.
The annotation: a caption that says what you found
Every exercise chunk in the notebook starts like this (line 133):
#| fig-cap: "ANNOTATION HERE"
# Code here#| fig-cap: is a chunk option. It’s read by Quarto when you render the notebook (the Render button), not by R, so it must be the first line of the chunk, and you’ll only see the caption in the rendered document. Replace ANNOTATION HERE with one sentence about your plot. **…** makes text bold, so the solutions write "**Figure 1:** …".
Compare two captions for the same histogram:
| Caption | |
|---|---|
| “Figure 1: Histogram of cube test scores.” | Describes the plot. The reader can see that it’s a histogram. |
| “Figure 1: Most students score between 5 and 7 on the cubes test.” | Says what it shows. That’s the finding. |
A good caption is the finding, in one sentence. Test it: cover the plot. Does the caption alone tell someone what you found?
Which chart for which question?
Start from the question you want to answer, then pick the chart. The six exercises cover six common questions:
| Question | Chart | ggplot geom | Exercise |
|---|---|---|---|
| How is one number spread out? | Histogram | geom_histogram() |
2.1 |
| How many are in each group? | Bar chart | geom_col() or geom_bar() |
2.2 |
| Do two numbers move together? | Scatter plot | geom_point() or geom_jitter() |
2.3 |
| How does something change over time? | Line plot | geom_line() or geom_area() |
2.4 |
| How do groups compare (middle and spread)? | Box plot | geom_boxplot() |
2.5 |
| How do groups compare (the whole shape)? | Density plot | geom_density() |
2.6 |
Part 2: The six design exercises
About an hour. For each one: write a theme function, the plot, and a caption. Try first; then open “Show the code”.
2.1 A histogram of cube scores
Make a histogram of t02_cubes, with a theme function, readable axis labels and a caption.
A histogram splits the range of scores into equal slices (bins), counts how many children fall in each, and draws one bar per bin. You only give ggplot one column, on the x axis; the counts on the y axis are worked out for you.
Two arguments of geom_histogram() that confuse everybody: colour = is the outline of each bar, fill = is the inside.
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")alpha = 0.5 makes the fill half see-through. The theme removes the vertical grid lines, which a histogram doesn’t need. The solutions also add as_tibble() |> after hs_data; it does no harm, but hs_data is already a tibble.
72% of the children score between 5 and 7, with a peak around 6 and a longer tail to the right. The solutions’ caption says the scores are “normally distributed”; “roughly bell-shaped, with a longer right tail” is more accurate, and “most students score between 5 and 7” tells the reader more.
The number of bins is a design choice. Too few and the shape disappears; too many and you see noise. ggplot’s default is 30, and it prints a message (stat_bin() using bins = 30) to remind you to choose. Try a few values.
With 5 bins, everything sits in a few blocks. With 60, there are gaps, because the cube scores only take 25 different values (quarter points). 20 shows the shape.
2.2 A bar chart of students per school
Count the students in each school, and plot the counts as a bar chart.
This is two jobs: summarise with count() (Lab 1), then plot the summary. The plot gets a two-row table, not the 301 children:
geom_col() draws one bar per row, as long as the number you give it. Put n on the x axis and school on the y axis, and the bars lie on their side, so the names are easy to read.
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")geom_col() needs the counts in the data, so you count() first. geom_bar() counts the rows itself: hs_data |> ggplot(aes(y = school)) + geom_bar() draws the same chart without count(). Use whichever you find clearer.
Why do bar charts (unlike scatter plots) have to start at zero?
Because ggplot can’t draw them any other way
ggplot could; it chooses zero on purpose.
Because the reader compares the lengths of the bars
Yes. If the axis started at 140, Pasteur’s bar (156) would look three times as long as Grant-White’s (145). The length must stand for the number.
It’s just a convention with no reason behind it
There’s a good reason: readers judge bars by their length.
2.3 A scatter plot, coloured by school
Plot t01_visperc (x) against t03_frmbord (y), with a different colour for each school.
To colour by a column, add colour = school inside aes(). ggplot then picks one colour per school and adds a legend.
Inside aes() or outside? Anything that should change with the data goes inside aes(): aes(colour = school) means “colour depends on the school”. Anything fixed goes outside, in the geom: geom_point(colour = "navy") means “make every dot navy”.
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"
)scale_colour_cosmic()swaps the default colours for a palette fromggsci. Others:scale_colour_npg(),scale_colour_lancet(),scale_colour_simpsons(). Usescale_colour_…for points and lines,scale_fill_…for bars and areas.colour = "School"insidelabs()sets the legend’s title.legend.position = "bottom"in the theme moves the legend under the plot.
The cloud slopes upwards, but it’s wide: the correlation is 0.37 (1 would be a perfect line, 0 no relationship). “Tend to” is the right strength of claim. The two schools overlap completely, which is a finding too: there’s no school difference here.
Why geom_jitter() and not geom_point()? Test scores come in fixed steps, so the 301 children share only 177 positions in this plot. With geom_point(), children with the same two scores sit exactly on top of each other and you can’t see them. This is called overplotting.
geom_jitter() moves each dot a tiny random amount, so stacked dots spread out. alpha = 0.5 makes the dots half see-through, so where several overlap, the spot looks darker. Jitter is random, so the picture changes slightly every time you run it; put set.seed(1) before the plot to fix it.
2.4 A line plot of results per year
Count the rows of nuijten2020 by year, then draw a line (or area) plot of the counts.
Same two jobs as 2.2: count(year) makes a table with one row per year and a column n; then geom_line() joins the points in order of year. nuijten2020 is a plain data frame, so pipe it through as_tibble() first, or it prints all 2,443 rows.
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, so no legend. For an area plot, use geom_area(fill = "midnightblue", alpha = 0.5) instead of geom_line().
Two things to be careful about:
- What does
count()count? Rows. One row here is one result, not one study: the 2,443 rows come from 1,917 different studies, because some studies report several results. The solutions’ y label says “Number of Studies”; “Number of results” is correct. (The plot above uses that label.) - Why the drop after 2008? The peak is in 2005 (126 results). After that the line falls fast, but not because people stopped studying intelligence. The reviews in this data set were done by about 2014, and recent studies hadn’t been included in reviews yet. The drop is about how the data were collected, not about the world.
A friend looks at Figure 4 and says: “Intelligence research collapsed after 2008.” What’s the best reply?
“Yes, the line clearly falls.”
The line falls, but the plot counts results that ended up in reviews, not all research.
“The data stop where the reviews stopped collecting. Recent studies weren’t in them yet.”
Yes. Always ask how the data were collected before reading a trend.
“The y axis should start at zero.”
It does already. The problem is what the data cover, not the axis.
The notebook calls this data set “longitudinal”. Strictly it isn’t: longitudinal data follow the same people or units over time. Here each row is a different study, with the year it came out. A line of counts per year is still fine.
2.5 Box plots by grade
Compare the figure recognition scores (t16_figrrecg) of grade 7 and grade 8. The task at line 191 says “use a histogram”; it means a box plot, which is what the section is about.
A box plot squeezes a group into five numbers:
- The box holds the middle half of the children; the line inside is the median.
- The whiskers reach out to the furthest child who is still within 1.5 box-heights of the box.
- Anyone further out is an outlier, drawn as a single dot: worth a second look.
Because each group becomes one small box, several groups fit side by side. What a box plot hides is the shape: two peaks look the same as one. That’s what 2.6 is for.
One trap. grade is stored as a number (7 or 8). Given a number on the x axis, ggplot draws one box for everybody and warns Continuous x aesthetic – did you forget aes(group = …)? Wrap it in as.factor() to turn 7 and 8 into two groups:
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")Two lines of the solution do nothing: scale_fill_bmj() changes the fill colours, but nothing is mapped to fill; and alpha = 0.75 has no fill to fade. To use the BMJ colours, add fill = as.factor(grade) inside aes(). Then legend.position = "none" makes sense too: the x axis already names the groups.
The plot above adds fill = as.factor(grade), so the BMJ colours show. The medians are 6.57 (grade 7) and 6.86 (grade 8): a small difference, and the boxes overlap a lot. One grade 7 child scored below 1, far from everyone else: an outlier.
2.6 Density plots by gender
Show the distribution of t23_series (series completion) for boys and girls, as density plots.
A density plot is a smoothed histogram: a curve instead of bars. With one curve per group, you can compare the whole shape of the groups. Two steps:
- Make a column with words.
femaleis 1 for male and 2 for female.if_else()turns that into labels: test, value if TRUE, value if FALSE. fill = genderinsideaes(), so each group gets its own colour;alphamakes the curves see-through so you can see both where they overlap.
mutate(gender = if_else(female == 2, "Female", "Male"))
- Choose between two values, row by row.
- The test.
==compares (Lab 1): isfemaleequal to 2? - The value where the test is TRUE.
- The value where it’s FALSE.
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)fill = NULL inside labs() removes the legend’s title: “Female” and “Male” speak for themselves.
The two curves lie almost on top of each other (average scores 2.08 for boys and 1.96 for girls). The solutions’ caption says “There are no differences”. A plot can’t show no difference, only a small one; “almost the same” is what we can honestly say.
Not a count of children. Each curve is scaled so that the area under it is 1. That makes groups of different sizes comparable: you compare shapes, not heights in children.
You write ggplot(aes(t23_series, fill = "gender")), with quotation marks. What happens?
One curve per gender, as before
No: with quotes, "gender" is just a piece of text, the same for every row.
One curve for everybody, and a legend with a single entry “gender”
Yes. Inside aes(), a column name goes without quotes. With quotes, every row gets the same value, the text “gender”.
An error
R doesn’t complain; it just doesn’t do what you meant. That’s what makes this mistake hard to spot.
Part 3: Design principles
About 15 minutes. The notebook ends with five principles (lines 215–229). Here they are with today’s examples.
Five principles for any chart
| Principle | What it means | Today’s example |
|---|---|---|
| Accessibility | Works for colour-blind readers and in black and white. Use shape or position as well as colour. | Below |
| Clarity | Every element earns its place. Remove what you don’t need. | Removing grid lines in every theme function; jitter and alpha against overplotting |
| Context | Enough to understand the plot on its own: labels in words, units, a caption, the source. | labs() and the captions |
| Consistency | Same scales, colours and style across related plots. | Theme functions you reuse |
| Focus | Point the reader to the finding: colour or size for what matters, grey for the rest. | The makeover below |
The goal is understanding, not showing off: clarity over complexity.
Colour for everyone
About 1 in 12 men and 1 in 200 women have a red–green colour vision deficiency. Here’s the scatter plot from 2.3 in red and green, the same plot as someone with that deficiency might see it (a simulation, made with colorspace::deutan()), and a fix:
In the middle plot the two schools become one. Two fixes, best used together:
- A colour-blind safe palette.
scale_colour_viridis_d()is built into ggplot. The Okabe–Ito colours (orange"#E69F00"and blue"#0072B2"above) can be set withscale_colour_manual(values = c("#E69F00", "#0072B2")). - A second cue that isn’t colour. Add
shape = schoolinsideaes(): circles for one school, triangles for the other. It also survives printing in black and white.
A makeover
Same data, same chart type. What changed?
- Context: axis labels in words instead of
as.factor(grade)andt16_figrrecg; the finding as the title. - Clarity: the grey background and grid lines are gone.
- Focus: the group the title talks about is in colour; the other is grey.
Pick your favourite of today’s six plots. Cover it and read only the caption: does it say what you found? Then check it against the five principles and change one thing.
Wrap-up
What you learned
The grammar of graphics Every ggplot is data + aesthetics (aes()) + a geom, joined with +. What changes with the data goes inside aes(); fixed settings go outside.
Pick the chart from the question Spread: histogram. Counts: bar chart. Two numbers: scatter plot. Time: line plot. Groups: box or density plot.
Look before you claim Ask what one row is; choose bins, jitter and as.factor() on purpose; ask how the data were collected before reading a trend.
Design for the reader A theme function for a consistent look, labels in words, a caption that says the finding, and colours everyone can tell apart.
One question to take away: pick your best plot from today. What would a reader learn from its caption alone?
Further reading
- R for Data Science (2e), free online: chapters 1 (data visualisation), 9 (layers) and 11 (communication).
- Claus Wilke, Fundamentals of Data Visualization, free online: choosing charts, colour and good design.
- Posit’s ggplot2 cheat sheet: every geom on two pages. Also under Help → Cheat Sheets in RStudio.
Glossary
Underlined words on this page are explained in this list. Click or tap one anywhere on the page to see what it means and where it was first explained.
| Word | Meaning |
|---|---|
| aesthetics | The link between a column and something you see: x position, y position, colour, fill, shape. Set inside aes() |
| alpha | How see-through something is: 0 is invisible, 1 is solid |
| bins | The equal slices a histogram splits the scores into. Each bar counts the rows in one bin |
| box plot | A chart that shows a group as a box (the middle half), a median line, whiskers and outliers |
| chunk option | A line starting with #\| at the top of a chunk, read by Quarto when rendering. fig-cap sets the caption |
| correlation | A number from −1 to 1 for how closely two numbers move together. 0 means no straight-line relationship |
| density plot | A smoothed histogram: a curve whose area is 1, useful for comparing the shape of groups |
| geom | The shape ggplot draws for each row: points, bars, lines, boxes |
| grammar of graphics | The idea behind ggplot: a plot is data + aesthetics + geoms, built up in layers |
| histogram | A chart of how one number is spread out: bars that count the rows in each bin |
| jitter | Moving each point a tiny random amount, so points on top of each other become visible |
| median | The middle value: half the group is above it, half below |
| outlier | A value far from the rest. In a box plot, any point beyond the whiskers |
| overplotting | Points hiding on top of each other in a scatter plot |
| theme | Everything about a plot’s look that isn’t data: background, grid lines, fonts, legend position |