
31 Slope graphs
theme_savedbythebell()
Graphs in this chapter use ggrewindr::theme_savedbythebell(), built from the Saved by the Bell logo: a black background with a royal blue frame, a yellow title, a white classroom panel, sky blue, pink, yellow, orange, royal blue, and navy marks, and a Yellowtail title.
31.1 Description
Slope graphs show changes in a numeric value (displayed on the y axis) typically over two points in time (along the x axis). The values for each group or unit of measurement are connected by lines, and any differences between the two time points are represented by the slope of the lines (hence the name, ‘slope chart’).
We can build slope graphs in ggplot2 using the geom_line() and geom_point() functions.
31.2 Set up
PACKAGES
Install packages.
show/hide
library(ggplot2)
library(dplyr) # for data manipulation
library(tidyr) # for expand_grid()DATA
Mr. Belding’s Bayside High gave us six students with very different relationships to homework: Zack scheming his way out of it, Screech and Jessie acing everything, and Slater and Kelly somewhere in between. We’ll simulate ten biology quizzes and ten history quizzes for each student in the fall of 1990 and the spring of 1991.
Each student gets an average score for each semester (avg_score). Zack and Slater improve in the spring, Lisa slips a little, and Kelly and Jessie stay exactly the same. rnorm() draws each quiz score around those averages, and pmin() caps the scores at 100. Setting the seed with set.seed() means you’ll get the same 240 quizzes every time you run the code below.
show/hide
set.seed(1989) # same quiz scores every time the code runs
bayside_quizzes <- expand_grid(
student = c("Zack", "Kelly", "Slater", "Jessie", "Lisa", "Screech"), # six Bayside students
semester = c("Fall 1990", "Spring 1991"), # two semesters
subject = c("Biology", "History"), # two subjects
quiz = 1:10 # ten quizzes in each subject
) |>
mutate(
student = factor(student, levels = unique(student)), # keep the order above
avg_score = case_when( # each student's average score
student == "Zack" ~ if_else(semester == "Fall 1990", 70, 80), # improves
student == "Kelly" ~ 82, # holds steady
student == "Slater" ~ if_else(semester == "Fall 1990", 72, 78), # improves
student == "Jessie" ~ 91, # holds steady
student == "Lisa" ~ if_else(semester == "Fall 1990", 84, 81), # slips a little
student == "Screech" ~ if_else(semester == "Fall 1990", 93, 95) # improves a little
),
score = round(pmin(100, rnorm(n(), mean = avg_score, sd = 8))) # no score above 100
)
glimpse(bayside_quizzes)
#> Rows: 240
#> Columns: 6
#> $ student <fct> Zack, Zack, Zack, Zack, Zack, …
#> $ semester <chr> "Fall 1990", "Fall 1990", "Fal…
#> $ subject <chr> "Biology", "Biology", "Biology…
#> $ quiz <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,…
#> $ avg_score <dbl> 70, 70, 70, 70, 70, 70, 70, 70…
#> $ score <dbl> 79, 79, 55, 68, 65, 67, 72, 74…A slope graph needs one value per student per semester, so we’ll average the 20 quizzes in each semester and store the results in bayside_slope.
show/hide
bayside_slope <- bayside_quizzes |>
group_by(semester, student) |> # one group per student per semester
summarise(avg_score = mean(score)) |> # average across both subjects
ungroup()
glimpse(bayside_slope)
#> Rows: 12
#> Columns: 3
#> $ semester <chr> "Fall 1990", "Fall 1990", "Fal…
#> $ student <fct> Zack, Kelly, Slater, Jessie, L…
#> $ avg_score <dbl> 70.00, 83.70, 72.55, 88.30, 83…31.3 Distribution
The slope of each line is the difference between two averages. Averages are much steadier than single quiz scores, but they’re not perfectly steady, so a slope graph can show a small rise or fall even when nothing changed. Below we’ll move from the quizzes, to a picture, to the formula, and work out how big a slope needs to be before we take it seriously.
COUNT IT
Start with Zack’s first five biology quizzes from the fall.
show/hide
bayside_quizzes |>
filter(student == "Zack", semester == "Fall 1990") |>
select(subject, quiz, score) |>
head(5)Single quizzes bounce around their averages by about 6 points, and a few miss by more than 14. Below we compare each student’s fall and spring averages (change) with the change we built into the simulation (true_change).
show/hide
slope_changes <- bayside_quizzes |>
group_by(student, semester) |>
summarise(avg = mean(score), truth = first(avg_score),
.groups = "drop") |>
pivot_wider(names_from = semester, values_from = c(avg, truth)) |>
mutate(change = `avg_Spring 1991` - `avg_Fall 1990`,
true_change = `truth_Spring 1991` - `truth_Fall 1990`) |>
select(student, change, true_change)
slope_changesZack’s and Slater’s averages went up, just as they should. But Kelly’s average dropped by about 4.5 points, even though her true average didn’t change at all.
DRAW IT
The graph below shows every quiz for Zack and Kelly as a faded point, with the slope graph lines drawn through their semester averages. The points are jittered a little to the side so they don’t stack. Zack’s cloud of points shifts up in the spring. Kelly’s two clouds sit in about the same place. Her line slopes down only because her fall quizzes happened to land a little high (about 84) and her spring quizzes a little low (about 79), while her true average stayed at 82.
show/hide
zack_kelly <- bayside_quizzes |>
filter(student %in% c("Zack", "Kelly"))
ggplot(zack_kelly, aes(x = semester, y = score, color = student)) +
geom_jitter(width = 0.08, height = 0, alpha = 1 / 3, size = 2) +
stat_summary(aes(group = student), fun = mean, geom = "line",
linewidth = 2) +
stat_summary(fun = mean, geom = "point", size = 4) +
labs(x = NULL, y = "Quiz score", color = "Student")
NAME IT
Each quiz score is a draw from a normal distribution centered on the student’s average for that semester (and capped at 100):
\[ \text{score} \sim \text{Normal}(\mu_{\text{student, semester}}, \; \sigma = 8) \]
An average of \(n = 20\) quizzes has a standard deviation of \(\sigma / \sqrt{n} = 8 / \sqrt{20} \approx 1.8\) points (the standard error). A slope is the difference between two of these averages, so its standard deviation is \(\sqrt{1.8^2 + 1.8^2} \approx 2.5\) points. About 95% of slopes land within two standard deviations (about 5 points) of the true change. Kelly’s drop is inside that range, while Zack’s and Slater’s gains are large enough to stand out. Try changing quiz = 1:10 to quiz = 1:40 and the noise in every slope is cut in half.
31.4 Grammar
CODE
Create labels with
labs()Initialize the graph with
ggplot()and providedataMap
semesterto thex,avg_scoretoy, andstudenttogroupAdd a
geom_line()layer, mappingstudenttocolor, and setting thelinewidthto2Add a
geom_point()layer, mappingstudenttocolor, and settingsizeto4We’ll move the
xaxis to the"top"of the graph withscale_x_discrete()
show/hide
labs_slope <- labs(
title = "Bayside High quizzes",
caption = "Simulated data",
subtitle = "Fall 1990 & Spring 1991",
x = NULL, y = "Average quiz score",
color = "Student")
ggp2_slope <- ggplot(data = bayside_slope,
mapping = aes(x = semester,
y = avg_score,
group = student)) +
geom_line(aes(color = student),
linewidth = 2, show.legend = FALSE) +
geom_point(aes(color = student),
size = 4) +
scale_x_discrete(position = "top")
ggp2_slope +
labs_slopeGRAPH

31.5 More info
We can also use faceting with slope graphs to add a third categorical variable.
DATA
We’ll use the bayside_quizzes data again, but this time we group it by semester, student, and subject.
show/hide
bayside_grp_slope <- bayside_quizzes |>
group_by(semester, student, subject) |> # one group per student, semester, and subject
summarise(avg_score = mean(score)) |> # average across the ten quizzes
ungroup()
glimpse(bayside_grp_slope)
#> Rows: 24
#> Columns: 4
#> $ semester <chr> "Fall 1990", "Fall 1990", "Fal…
#> $ student <fct> Zack, Zack, Kelly, Kelly, Slat…
#> $ subject <chr> "Biology", "History", "Biology…
#> $ avg_score <dbl> 69.4, 70.6, 86.6, 80.8, 70.9, …GRAPH
Create labels with
labs()Initialize the graph with
ggplot()and providedataMap
semesterto thex,avg_scoretoy, andstudenttogroupAdd a
geom_line()layer, mappingstudenttocolor, and setting thelinewidthto2Add a
geom_point()layer, mappingstudenttocolor, and settingsizeto4We’ll move the
xaxis to the"top"of the graph withscale_x_discrete()Finally, we facet the graph by
subject, adjust thesizeof the text, and move the legend to the"bottom"of the graph.
show/hide
labs_grp_slope <- labs(
title = "Bayside High quizzes",
caption = "Simulated data",
subtitle = "Fall 1990 & Spring 1991, by subject",
x = NULL, y = "Average quiz score",
color = "Student")
ggp2_grp_slope <- ggplot(data = bayside_grp_slope,
mapping = aes(x = semester,
y = avg_score,
group = student)) +
geom_line(aes(color = student),
linewidth = 2, show.legend = FALSE) +
geom_point(aes(color = student),
size = 4) +
scale_x_discrete(position = "top") +
facet_wrap(. ~ subject,
ncol = 2) +
theme(
legend.position = "bottom",
axis.text.x = element_text(size = 9),
axis.text.y = element_text(size = 9),
strip.text = element_text(size = 10))
ggp2_grp_slope +
labs_grp_slope
Each subject average is built from only ten quizzes, so these slopes are noisier than the ones above (their standard deviation is about \(\sqrt{2} \times 8 / \sqrt{10} \approx 3.6\) points). That’s why Jessie’s history line climbs while her biology line falls, even though her true average is the same in both semesters.