Figures That Answer Data Questions
A figure can reveal a pattern while obscuring how many observations it represents. Several people with identical scores may appear at one point, and a line may connect measurements across an occasion with no recorded score. To interpret the display, we need to know how its points, bars, and lines relate to the underlying records. This chapter develops that relationship using ggplot2 in R and Matplotlib in Python. We begin by mapping table values to graphical marks, then examine numerical distributions, category and group comparisons, and repeated measurements. Throughout, we choose observations and scales to suit the question and check the figure against the table it represents.
18.1 From a table to graphical marks
How does test accuracy vary across the participants in the Stroop task? In the practice file, each participant contributes 192 test trials, identified as keyboard records in blocks 1 to 4. In those records, correct is 1 for a correct response and 0 for an incorrect response or a timeout. Each person’s point shows the proportion of those 192 trials they answered correctly.
The horizontal axis lists participants in identifier order. On the vertical axis, 1 means the participant answered every test trial correctly. Showing the full range from 0 to 1 makes the distance from perfect accuracy visible.
In participant_accuracy, each row summarizes one person’s test trials. For keyboard trials in blocks 1 through 4, summarise() with .by = participant counts trials and correct responses for each person. mutate() divides the number correct by the number of trials. The count and range checks establish that the table contains one accuracy value per person, each based on 192 trials.
The plot translates those rows into positions. In ggplot2, ggplot() creates a plot object and + adds layers, scales, or labels. Here aes() maps participant ID to horizontal position and accuracy to height. geom_point() adds a layer with one point for each row. Setting colour = "#0072B2" outside aes() makes every point blue.
The remaining settings make the comparison readable. scale_y_continuous() sets the vertical range and labs() names the axes. theme_minimal() sets the background and grid, and theme() rotates the participant labels. ggsave() writes the plot to PNG and PDF files in figures/ch18.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
library(tidyverse)
trials <- read_csv(
"data/practice/trials.csv",
col_types = cols_only(
participant = col_character(),
trial_type = col_character(),
block = col_integer(),
correct = col_integer()
),
na = "",
trim_ws = FALSE
)
participant_accuracy <- trials |>
filter(trial_type == "keyboard" & block %in% 1:4) |>
summarise(n_test = n(), n_correct = sum(correct), .by = participant) |>
mutate(accuracy = n_correct / n_test) |>
arrange(participant)
c(
rows = nrow(participant_accuracy),
participants = n_distinct(participant_accuracy$participant),
missing_accuracy = sum(is.na(participant_accuracy$accuracy))
)
range(participant_accuracy$n_test)
accuracy_plot <- ggplot(participant_accuracy, aes(x = participant, y = accuracy)) +
geom_point(colour = "#0072B2", size = 2) +
scale_y_continuous(limits = c(0, 1)) +
labs(x = "Participant", y = "Accuracy (proportion correct)") +
theme_minimal(base_size = 11) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5))
dir.create("figures/ch18", recursive = TRUE, showWarnings = FALSE)
ggsave(
"figures/ch18/fig-18-01.png", accuracy_plot,
width = 6.5, height = 4.2, units = "in", dpi = 300
)
ggsave(
"figures/ch18/fig-18-01.pdf", accuracy_plot,
width = 6.5, height = 4.2, units = "in"
)
1
2
3
rows participants missing_accuracy
40 40 0
[1] 192 192
Figure 18.1. Test accuracy for 40 participants, drawn with ggplot2. Each point shows the proportion of one person’s 192 test trials answered correctly.
With the .venv Python session active, install matplotlib and numpy through Packages: Install Package. After the Polars table is filtered to keyboard trials in blocks 1 through 4, agg() counts trials and correct responses for each participant. with_columns() divides the number correct by the number of trials, giving one accuracy value per person.
Matplotlib draws from lists and NumPy arrays. A NumPy array stores values of one type in one or more dimensions. Here to_list() returns the identifiers, and to_numpy() returns the accuracies. Both conversions follow the sorted table order, so each identifier remains paired with its accuracy. The checks compare the number of IDs with the number of distinct IDs and test whether any accuracies are missing.
plt.subplots() returns the figure, which is the whole image, and an Axes object, the plotting area. In draw_accuracy(), ax.scatter() draws one point per participant and returns the collection of points. ax.set_ylim(0, 1) sets the range of the vertical scale, which maps accuracy to height. The function returns both the figure and the collection so we can read a point’s coordinates. fig.savefig() writes the figure to PNG and PDF, and plt.close() closes it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import polars as pl
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
trials = pl.read_csv(
"data/practice/trials.csv",
columns=["participant", "trial_type", "block", "correct"],
infer_schema=False,
schema_overrides={"block": pl.Int64, "correct": pl.Int64},
)
participant_accuracy = (
trials.filter(
(pl.col("trial_type") == "keyboard") & pl.col("block").is_in([1, 2, 3, 4])
)
.group_by("participant")
.agg(n_test=pl.len(), n_correct=pl.col("correct").sum())
.with_columns(accuracy=pl.col("n_correct") / pl.col("n_test"))
.sort("participant")
)
participants = participant_accuracy["participant"].to_list()
accuracy = participant_accuracy["accuracy"].to_numpy()
(len(participants), participant_accuracy["participant"].n_unique(), accuracy.dtype)
(int(np.isnan(accuracy).sum()), participant_accuracy["accuracy"].null_count())
(participants[28], float(accuracy[28]))
def draw_accuracy(participants, accuracy):
fig, ax = plt.subplots(figsize=(6.5, 4.2), layout="constrained")
points = ax.scatter(participants, accuracy, color="#0072B2")
ax.set_ylim(0, 1)
ax.set_xlabel("Participant", fontsize=11)
ax.set_ylabel("Accuracy (proportion correct)", fontsize=11)
ax.tick_params(axis="x", labelrotation=90)
ax.grid(color="0.9")
ax.set_axisbelow(True)
return fig, points
Path("figures/ch18").mkdir(parents=True, exist_ok=True)
fig, points = draw_accuracy(participants, accuracy)
fig.savefig("figures/ch18/fig-18-02.png", dpi=300)
fig.savefig("figures/ch18/fig-18-02.pdf")
plt.close(fig)
1
2
3
(40, 40, dtype('float64'))
(0, 0)
('sub-029', 0.2916666666666667)
Figure 18.2. Test accuracy for 40 participants, drawn with Matplotlib. Each point shows the proportion of one person’s 192 test trials answered correctly.
The point for sub-029 lies far below the others. Its height should equal the proportion correct in that participant’s summary row. In ggplot2, layer_data() returns the coordinates in the plotted layer. In Matplotlib, get_offsets() returns the positions in the point collection.
1
2
3
4
filter(participant_accuracy, participant == "sub-029")
layer_data(accuracy_plot) |>
filter(x == 29) |>
select(x, y)
1
2
3
4
5
6
# A tibble: 1 × 4
participant n_test n_correct accuracy
<chr> <int> <int> <dbl>
1 sub-029 192 56 0.292
x y
1 29 0.2916667
1
2
participant_accuracy.filter(pl.col("participant") == "sub-029")
points.get_offsets()[28].tolist()
1
2
3
4
5
6
7
8
9
shape: (1, 4)
┌─────────────┬────────┬───────────┬──────────┐
│ participant ┆ n_test ┆ n_correct ┆ accuracy │
│ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ i64 ┆ f64 │
╞═════════════╪════════╪═══════════╪══════════╡
│ sub-029 ┆ 192 ┆ 56 ┆ 0.291667 │
└─────────────┴────────┴───────────┴──────────┘
[28.0, 0.2916666666666667]
The point for sub-029 is at 56/192, or about 0.2917, in both plots. Its horizontal coordinate is 29 in ggplot2 and 28 in Matplotlib because category numbering starts at 1 and 0, respectively. To find which trials were incorrect or timed out, we would need the trial records. The low accuracy alone does not establish that the records should be excluded.
Two measurements per person
How do the panel’s wave-1 depression and anxiety totals relate? In this scatter plot, both axes are measurements. Depression scores run from 0 to 18 on the horizontal axis and anxiety scores from 0 to 15 on the vertical axis. Only people with both totals can appear. Points directly above one another show how much anxiety scores vary at the same depression total.
In R, the import reads the score columns as integers, and count() counts people according to which totals are present. baseline_pairs contains each person’s id and both scores wherever both are recorded. Counting distinct IDs gives the number of people, while counting distinct score pairs gives the number of positions they occupy.
ggplot() maps one score to each axis. The scale breaks place tick labels every 3 points, and the axis titles give the possible score ranges. Each row produces a point, but rows with the same pair of scores produce points at the same position.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
panel <- read_csv(
"data/practice/panel_wide.csv",
col_types = cols(
dep_w1 = col_integer(),
dep_w2 = col_integer(),
dep_w3 = col_integer(),
anx_w1 = col_integer(),
.default = col_character()
),
na = "",
trim_ws = FALSE
)
count(panel, has_dep = !is.na(dep_w1), has_anx = !is.na(anx_w1))
baseline_pairs <- panel |>
filter(!is.na(dep_w1) & !is.na(anx_w1)) |>
select(id, dep_w1, anx_w1)
c(
people = nrow(baseline_pairs),
ids = n_distinct(baseline_pairs$id),
positions = nrow(distinct(baseline_pairs, dep_w1, anx_w1))
)
pair_plot <- ggplot(baseline_pairs, aes(x = dep_w1, y = anx_w1)) +
geom_point(colour = "#0072B2", size = 2) +
scale_x_continuous(breaks = seq(0, 18, by = 3)) +
scale_y_continuous(breaks = seq(0, 15, by = 3)) +
labs(
x = "Depression total at wave 1 (possible range 0 to 18)",
y = "Anxiety total at wave 1 (possible range 0 to 15)"
) +
theme_minimal(base_size = 11)
ggsave(
"figures/ch18/fig-18-03.png", pair_plot,
width = 6.5, height = 4.2, units = "in", dpi = 300
)
ggsave(
"figures/ch18/fig-18-03.pdf", pair_plot,
width = 6.5, height = 4.2, units = "in"
)
1
2
3
4
5
6
7
8
9
# A tibble: 4 × 3
has_dep has_anx n
<lgl> <lgl> <int>
1 FALSE FALSE 18
2 FALSE TRUE 21
3 TRUE FALSE 14
4 TRUE TRUE 262
people ids positions
262 262 150
Figure 18.3. Wave-1 depression and anxiety totals of the 262 panel participants with both totals, one point per person, drawn with ggplot2. People with the same two totals share one position.
In Polars, grouping by the two presence tests counts people with both scores, one score, or neither. drop_nulls(["dep_w1", "anx_w1"]) selects people with both totals, and select() includes their IDs. Two people with the same scores have different IDs but share a position in the plot.
The two to_numpy() calls read the same rows in the same order, so ax.scatter() pairs each person’s depression score with their anxiety score. range(0, 19, 3) places horizontal ticks from 0 to 18 in steps of 3. The two dimensions of get_offsets().shape give the number of plotted points and the number of coordinates per point.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
panel = pl.read_csv(
"data/practice/panel_wide.csv",
infer_schema=False,
schema_overrides={
"dep_w1": pl.Int64, "dep_w2": pl.Int64,
"dep_w3": pl.Int64, "anx_w1": pl.Int64,
},
)
panel.group_by(
has_dep=pl.col("dep_w1").is_not_null(),
has_anx=pl.col("anx_w1").is_not_null(),
).agg(n=pl.len()).sort("has_dep", "has_anx")
baseline_pairs = panel.drop_nulls(["dep_w1", "anx_w1"]).select(
"id", "dep_w1", "anx_w1"
)
(
baseline_pairs.height,
baseline_pairs["id"].n_unique(),
baseline_pairs.select("dep_w1", "anx_w1").n_unique(),
)
depression = baseline_pairs["dep_w1"].to_numpy()
anxiety = baseline_pairs["anx_w1"].to_numpy()
(depression.dtype, anxiety.dtype, len(depression), len(anxiety))
def draw_pairs(depression, anxiety):
fig, ax = plt.subplots(figsize=(6.5, 4.2), layout="constrained")
points = ax.scatter(depression, anxiety, color="#0072B2")
ax.set_xlabel("Depression total at wave 1 (possible range 0 to 18)", fontsize=11)
ax.set_ylabel("Anxiety total at wave 1 (possible range 0 to 15)", fontsize=11)
ax.set_xticks(range(0, 19, 3))
ax.set_yticks(range(0, 16, 3))
ax.grid(color="0.9")
ax.set_axisbelow(True)
return fig, points
fig, points = draw_pairs(depression, anxiety)
fig.savefig("figures/ch18/fig-18-04.png", dpi=300)
fig.savefig("figures/ch18/fig-18-04.pdf")
plt.close(fig)
points.get_offsets().shape
1
2
3
4
5
6
7
8
9
10
11
12
13
14
shape: (4, 3)
┌─────────┬─────────┬─────┐
│ has_dep ┆ has_anx ┆ n │
│ --- ┆ --- ┆ --- │
│ bool ┆ bool ┆ u32 │
╞═════════╪═════════╪═════╡
│ false ┆ false ┆ 18 │
│ false ┆ true ┆ 21 │
│ true ┆ false ┆ 14 │
│ true ┆ true ┆ 262 │
└─────────┴─────────┴─────┘
(262, 262, 150)
(dtype('int64'), dtype('int64'), 262, 262)
(262, 2)
Figure 18.4. Wave-1 depression and anxiety totals of the 262 panel participants with both totals, one point per person, drawn with Matplotlib. People with the same two totals share one position.
Of the 315 people, 262 have both scores. Another 14 have only a depression score, 21 only an anxiety score, and 18 neither. The scatter plot therefore describes the relationship between the two totals for the 262 people with both measurements.
At a depression total of 10, anxiety totals range from 0 to 15. Identical score pairs overlap: the 12 people with two zeros appear as one dot at (0, 0), and the 262 people occupy 150 positions. The positions reveal score combinations, but their number understates the number of people. Checking how the totals were calculated would require the individual item responses.
18.2 Showing numerical distributions
The scatter plot needs both scores. For a histogram of depression alone, we can also include the 14 people with a depression total but no anxiety total. The mean of the 276 available scores is about 6.64 points, but it does not tell us how many people scored from 0 to 2. A histogram groups scores into intervals called bins and shows the count in each.
The bin edges are 0, 3, 6, 9, 12, 15, and 18. Many whole-number totals fall exactly on an edge. Each bin includes its lower edge, so a score of 6 goes with 7 in the bin from 6 to 9. Only the last bin includes its upper edge, 18. It covers four possible totals and the others cover three. Every observed total belongs to exactly one bin.
In R, observed contains every row of panel with a depression total, including people without an anxiety total. After the availability, mean, and range checks, seq() builds the edges. geom_histogram() takes these edges as its breaks, with closed = "left" for the inclusion rule.
To verify that the bars count the intended scores, layer_data() extracts the plotted counts and cut() independently assigns each total to a bin. The settings right = FALSE and include.lowest = TRUE apply the same inclusion rule. In the output, [0,3) excludes 3 and [15,18] includes 18.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
observed <- filter(panel, !is.na(dep_w1))
c(
rows = nrow(panel),
observed = nrow(observed),
unavailable = sum(is.na(panel$dep_w1))
)
mean(observed$dep_w1)
range(observed$dep_w1)
edges <- seq(0, 18, by = 3)
edges
histogram_plot <- ggplot(observed, aes(x = dep_w1)) +
geom_histogram(
breaks = edges, closed = "left", fill = "#0072B2", colour = "white"
) +
scale_x_continuous(breaks = edges) +
labs(x = "Depression total at wave 1 (points)", y = "Number of observed totals") +
theme_minimal(base_size = 11)
ggsave(
"figures/ch18/fig-18-05.png", histogram_plot,
width = 6.5, height = 4.2, units = "in", dpi = 300
)
ggsave(
"figures/ch18/fig-18-05.pdf", histogram_plot,
width = 6.5, height = 4.2, units = "in"
)
bar_counts <- layer_data(histogram_plot)$count
bar_counts
sum(bar_counts)
count(observed, bin = cut(dep_w1, breaks = edges, right = FALSE, include.lowest = TRUE))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
rows observed unavailable
315 276 39
[1] 6.641304
[1] 0 18
[1] 0 3 6 9 12 15 18
[1] 84 45 48 47 30 22
[1] 276
# A tibble: 6 × 2
bin n
<fct> <int>
1 [0,3) 84
2 [3,6) 45
3 [6,9) 48
4 [9,12) 47
5 [12,15) 30
6 [15,18] 22
Figure 18.5. Wave-1 depression totals for 276 people, drawn with ggplot2. The 3-point bins include their lower edge, and the final bin also includes 18. Another 39 people had no recorded score.
In Polars, panel.drop_nulls("dep_w1") selects everyone with an observed depression total, whether or not an anxiety total is available. to_numpy() converts these totals into an integer array, and np.arange(0, 19, 3) builds the edges through 18.
draw_bins() draws on the axes it receives, while draw_histogram() creates a figure around it. ax.hist() returns counts, edges, and bars. The code stores the counts and assigns each unused return value to _. With these edges, ax.hist() includes the lower edge of every bin and both edges of the last, matching the chosen rule.
For an independent count in Polars, // divides each score by 3 and rounds down. Multiplying by 3 gives the bin’s lower edge for all scores below 18. For a score of 18, clip(upper_bound=15) sets bin_start to 15. Grouping by bin_start then counts the scores in each bar.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
observed = panel.drop_nulls("dep_w1")
(panel.height, observed.height, panel["dep_w1"].null_count())
observed["dep_w1"].mean()
(observed["dep_w1"].min(), observed["dep_w1"].max())
depression = observed["dep_w1"].to_numpy()
edges = np.arange(0, 19, 3)
edges
def draw_bins(ax, depression, edges):
counts, _, _ = ax.hist(depression, bins=edges, color="#0072B2", edgecolor="white")
ax.set_xticks(edges)
ax.set_xlabel("Depression total at wave 1 (points)", fontsize=11)
ax.grid(axis="y", color="0.9")
ax.set_axisbelow(True)
return counts
def draw_histogram(depression, edges):
fig, ax = plt.subplots(figsize=(6.5, 4.2), layout="constrained")
counts = draw_bins(ax, depression, edges)
ax.set_ylabel("Number of observed totals", fontsize=11)
return fig, counts
fig, bar_counts = draw_histogram(depression, edges)
fig.savefig("figures/ch18/fig-18-06.png", dpi=300)
fig.savefig("figures/ch18/fig-18-06.pdf")
plt.close(fig)
bar_counts.tolist()
int(bar_counts.sum())
observed.group_by(
bin_start=(pl.col("dep_w1") // 3 * 3).clip(upper_bound=15)
).agg(n=pl.len()).sort("bin_start")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
(315, 276, 39)
6.641304347826087
(0, 18)
array([ 0, 3, 6, 9, 12, 15, 18])
[84.0, 45.0, 48.0, 47.0, 30.0, 22.0]
276
shape: (6, 2)
┌───────────┬─────┐
│ bin_start ┆ n │
│ --- ┆ --- │
│ i64 ┆ u32 │
╞═══════════╪═════╡
│ 0 ┆ 84 │
│ 3 ┆ 45 │
│ 6 ┆ 48 │
│ 9 ┆ 47 │
│ 12 ┆ 30 │
│ 15 ┆ 22 │
└───────────┴─────┘
Figure 18.6. Wave-1 depression totals for 276 people, drawn with Matplotlib. The 3-point bins include their lower edge, and the final bin also includes 18. Another 39 people had no recorded score.
Changing only the bin width
How different will the same scores look in wider bins? Edges at 0, 6, 12, and 18 join neighboring bins in pairs. The scores and the rule for values on an edge are unchanged, so any difference in the bars comes from the grouping alone.
In R, each geom_histogram() layer receives its own breaks and a copy of the same totals with a bins column naming the width. facet_wrap() splits the rows by bins into panels, small plotting areas on a shared count scale.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
width_plot <- ggplot(mapping = aes(x = dep_w1)) +
geom_histogram(
data = mutate(observed, bins = "3-point bins"),
breaks = seq(0, 18, by = 3), closed = "left", fill = "#0072B2", colour = "white"
) +
geom_histogram(
data = mutate(observed, bins = "6-point bins"),
breaks = seq(0, 18, by = 6), closed = "left", fill = "#0072B2", colour = "white"
) +
facet_wrap(vars(bins)) +
scale_x_continuous(breaks = seq(0, 18, by = 3)) +
labs(x = "Depression total at wave 1 (points)", y = "Number of observed totals") +
theme_minimal(base_size = 11)
ggsave(
"figures/ch18/fig-18-07.png", width_plot,
width = 6.5, height = 4.2, units = "in", dpi = 300
)
ggsave(
"figures/ch18/fig-18-07.pdf", width_plot,
width = 6.5, height = 4.2, units = "in"
)
wide_counts <- layer_data(width_plot, i = 2)$count
wide_counts
sum(wide_counts)
1
2
[1] 129 95 52
[1] 276
Figure 18.7. The 276 observed wave-1 depression scores in 3-point and 6-point bins on a shared count scale, drawn with ggplot2.
In Python, plt.subplots(1, 2, sharey=True) creates two axes in one row with a shared count scale. draw_bins() fills each using the chosen edges. To check the relationship between the results, reshape(3, 2) arranges the six narrow counts in three pairs, and sum(axis=1) adds each pair.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def draw_widths(depression, narrow, wide):
fig, (narrow_ax, wide_ax) = plt.subplots(
1, 2, figsize=(6.5, 4.2), sharey=True, layout="constrained"
)
narrow_counts = draw_bins(narrow_ax, depression, np.arange(0, 19, narrow))
wide_counts = draw_bins(wide_ax, depression, np.arange(0, 19, wide))
narrow_ax.set_title(str(narrow) + "-point bins", fontsize=11)
wide_ax.set_title(str(wide) + "-point bins", fontsize=11)
narrow_ax.set_ylabel("Number of observed totals", fontsize=11)
return fig, narrow_counts, wide_counts
fig, narrow_counts, wide_counts = draw_widths(depression, 3, 6)
fig.savefig("figures/ch18/fig-18-08.png", dpi=300)
fig.savefig("figures/ch18/fig-18-08.pdf")
plt.close(fig)
wide_counts.tolist()
narrow_counts.reshape(3, 2).sum(axis=1).tolist()
1
2
[129.0, 95.0, 52.0]
[129.0, 95.0, 52.0]
Figure 18.8. The 276 wave-1 depression scores in 3-point and 6-point bins on a shared count scale, drawn with Matplotlib.
The first wide bar combines 84 scores from 0 to 2 with 45 from 3 to 5. Its height of 129 tells us how many people scored below 6. The narrower bars also show how many of them scored below 3.
Changing the visible range is a different operation from changing the bins. All six bars count observed totals; the 39 people without a total have no score to place in a bin. Zooming to scores from 0 to 15 should change the view without changing those counts.
In ggplot2, coord_cartesian(xlim = c(0, 15)) zooms in after the scores have been counted. Setting limits = c(0, 15) in scale_x_continuous() would exclude scores above 15 before binning. In Matplotlib, set_xlim(0, 15) changes the view after hist() has drawn the bars. get_height() reads the height of each bar in zoomed_fig.axes[0].patches.
1
2
zoomed_histogram <- histogram_plot + coord_cartesian(xlim = c(0, 15))
layer_data(zoomed_histogram)$count
1
[1] 84 45 48 47 30 22
1
2
3
4
zoomed_fig, _ = draw_histogram(depression, edges)
_ = zoomed_fig.axes[0].set_xlim(0, 15)
[int(bar.get_height()) for bar in zoomed_fig.axes[0].patches]
plt.close(zoomed_fig)
1
[84, 45, 48, 47, 30, 22]
After the zoom, all six bar heights are unchanged. The final bar still counts 22 people with scores from 15 to 18.
Durations on a logarithmic axis
Binning changes how scores are grouped. An axis scale changes how far apart values appear. For five constructed durations of 1, 2, 4, 8, and 16 seconds, the gaps on an ordinary axis grow from 1 to 8 seconds. On a base-2 logarithmic axis, the five positions are 0, 1, 2, 3, and 4. Equal distances now represent equal ratios. Each step here doubles the duration. This scale requires positive values, and its tick labels can still report seconds.
In R, each duration is placed at height 0, since the vertical position has no meaning. scale_y_continuous(breaks = NULL) removes the vertical tick marks. scale_x_continuous(transform = "log2") transforms the horizontal positions. The breaks argument lists the original durations so that the labels are in seconds. layer_data() reports these transformed positions in x.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
durations <- tibble(seconds = c(1, 2, 4, 8, 16))
duration_plot <- ggplot(durations, aes(x = seconds, y = 0)) +
geom_point(colour = "#0072B2", size = 3) +
scale_x_continuous(
transform = "log2", breaks = durations$seconds, minor_breaks = NULL
) +
scale_y_continuous(breaks = NULL) +
labs(x = "Duration in seconds (base-2 logarithmic spacing)", y = NULL) +
theme_minimal(base_size = 11)
ggsave(
"figures/ch18/fig-18-09.png", duration_plot,
width = 6.5, height = 2.2, units = "in", dpi = 300
)
ggsave(
"figures/ch18/fig-18-09.pdf", duration_plot,
width = 6.5, height = 2.2, units = "in"
)
layer_data(duration_plot) |>
select(x) |>
mutate(seconds = durations$seconds)
1
2
3
4
5
6
x seconds
1 0 1
2 1 2
3 2 4
4 3 8
5 4 16
Figure 18.9. Constructed durations of 1, 2, 4, 8, and 16 seconds on a base-2 logarithmic axis, drawn with ggplot2.
The transformed positions 0 through 4 give the five durations equal spacing, while the axis labels show the original seconds.
In Python, draw_durations() passes the durations to ax.scatter(), then set_xscale("log", base=2) sets the horizontal scale. set_xticks() places and labels ticks in seconds, and set_yticks([]) removes the vertical marks. In get_offsets()[:, 0], the slice selects the horizontal coordinate of every point. Applying the axis transformation to seconds gives the positions on the logarithmic scale.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
seconds = np.array([1, 2, 4, 8, 16])
def draw_durations(seconds):
fig, ax = plt.subplots(figsize=(6.5, 2.2), layout="constrained")
points = ax.scatter(seconds, np.zeros(len(seconds)), color="#0072B2", s=50)
ax.set_xscale("log", base=2)
ax.set_xticks(seconds, labels=[str(value) for value in seconds])
ax.set_yticks([])
ax.set_xlabel("Duration in seconds (base-2 logarithmic spacing)", fontsize=11)
ax.grid(color="0.9")
ax.set_axisbelow(True)
return fig, ax, points
fig, ax, points = draw_durations(seconds)
fig.savefig("figures/ch18/fig-18-10.png", dpi=300)
fig.savefig("figures/ch18/fig-18-10.pdf")
points.get_offsets()[:, 0].tolist()
ax.xaxis.get_transform().transform(seconds).tolist()
plt.close(fig)
1
2
[1.0, 2.0, 4.0, 8.0, 16.0]
[0.0, 1.0, 2.0, 3.0, 4.0]
Figure 18.10. Constructed durations of 1, 2, 4, 8, and 16 seconds on a base-2 logarithmic axis, drawn with Matplotlib.
The first list gives the durations in seconds. The second gives their positions on the base-2 scale. The gap from 8 to 16 seconds is as wide as the gap from 1 to 2 seconds because each step doubles the duration.
18.3 Comparing categories and groups visually
How common is each of the five ratings for SAT_1, the survey item about being mostly satisfied with life right now? The bars follow the scale from Strongly disagree through Disagree, Neutral, and Agree to Strongly agree. Each category has a place on the axis even if its count is zero. A blank records a skipped answer and -99 a refusal. Neither is a rating.
Each form with a rating counts once, including a second form from the same person. A bar’s height is the percentage of those forms with that answer. The vertical axis names the denominator, and the number above the bar gives the count.
In R, the import reads answers as text and duration as a number, converting blank fields to NA. case_when() classifies SAT_1 as skipped, refused, observed, or invalid. The observed answers become a factor in the order listed above. count(.drop = FALSE) returns a row for every level, including unused ones. Dividing each count by the total number of ratings gives the bar height.
The plot makes both the count and denominator explicit. The total, answered, appears in the axis label. geom_col() draws the calculated heights, and geom_text() writes the counts above them. scales::label_percent() formats the vertical ticks as percentages. The final check compares the plotted heights with the table proportions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
survey <- read_csv(
"data/practice/survey.csv",
col_types = cols(`Duration (in seconds)` = col_double(), .default = col_character()),
na = "",
trim_ws = FALSE,
locale = locale(encoding = "UTF-8")
)
agreement_levels <- c(
"Strongly disagree", "Disagree", "Neutral", "Agree", "Strongly agree"
)
sat_answers <- survey |>
select(ResponseId, answer = SAT_1) |>
mutate(
status = case_when(
is.na(answer) ~ "skipped",
answer == "-99" ~ "refused",
answer %in% agreement_levels ~ "observed",
.default = "invalid"
)
)
count(sat_answers, status)
sat_counts <- sat_answers |>
filter(status == "observed") |>
mutate(level = factor(answer, levels = agreement_levels, ordered = TRUE)) |>
count(level, .drop = FALSE) |>
mutate(proportion = n / sum(n))
sat_counts
answered <- sum(sat_counts$n)
sat_plot <- ggplot(sat_counts, aes(x = level, y = proportion)) +
geom_col(fill = "#0072B2") +
geom_text(aes(label = n), vjust = -0.5, size = 3.5) +
scale_y_continuous(labels = scales::label_percent(), limits = c(0, 0.4)) +
labs(
x = "Answer to SAT_1",
y = paste0("Percent of the ", answered, " answered responses")
) +
theme_minimal(base_size = 11)
ggsave(
"figures/ch18/fig-18-11.png", sat_plot,
width = 6.5, height = 4.2, units = "in", dpi = 300
)
ggsave(
"figures/ch18/fig-18-11.pdf", sat_plot,
width = 6.5, height = 4.2, units = "in"
)
all.equal(layer_data(sat_plot, i = 1)$y, sat_counts$proportion)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# A tibble: 3 × 2
status n
<chr> <int>
1 observed 492
2 refused 1
3 skipped 10
# A tibble: 5 × 3
level n proportion
<ord> <int> <dbl>
1 Strongly disagree 96 0.195
2 Disagree 65 0.132
3 Neutral 86 0.175
4 Agree 76 0.154
5 Strongly agree 169 0.343
[1] TRUE
Figure 18.11. Ratings of life satisfaction on SAT_1, drawn with ggplot2. Bar heights are percentages of the 492 forms with a rating. The labels give counts. Ten forms have a blank for this item and one records a refusal.
In Polars, the import reads the answers as text and blank fields as null. The first tuple checks agreement labels, skips, refusals, and the total row count. is_in() produces null for a blank, which sum() skips. Counting each listed label separately gives every category a row, even if its count is zero.
draw_agreement() passes the labels and calculated proportions to ax.bar() in that order. ax.bar_label() adds the counts. PercentFormatter(xmax=1, decimals=0) displays proportions as whole percentages. The checks read back the tick labels and bar heights so they can be compared with the table.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from matplotlib.ticker import PercentFormatter
survey = pl.read_csv(
"data/practice/survey.csv",
infer_schema=False,
schema_overrides={"Duration (in seconds)": pl.Int64},
empty_string_is_null=True,
encoding="utf8",
)
agreement_levels = [
"Strongly disagree",
"Disagree",
"Neutral",
"Agree",
"Strongly agree",
]
answers = survey["SAT_1"]
(
answers.is_in(agreement_levels).sum(),
answers.is_null().sum(),
(answers == "-99").sum(),
survey.height,
)
sat_counts = pl.DataFrame(
{
"level": agreement_levels,
"n": [(answers == level).sum() for level in agreement_levels],
}
).with_columns(proportion=pl.col("n") / pl.col("n").sum())
sat_counts
answered = sat_counts["n"].sum()
def draw_agreement(sat_counts, answered):
fig, ax = plt.subplots(figsize=(7.5, 4.2), layout="constrained")
bars = ax.bar(
sat_counts["level"].to_list(),
sat_counts["proportion"].to_list(),
color="#0072B2",
)
ax.bar_label(bars, labels=[str(n) for n in sat_counts["n"]], padding=3)
ax.set_ylim(0, 0.4)
ax.yaxis.set_major_formatter(PercentFormatter(xmax=1, decimals=0))
ax.set_xlabel("Answer to SAT_1", fontsize=11)
ax.set_ylabel(
"Percent of the " + str(answered) + " answered responses", fontsize=11
)
ax.grid(axis="y", color="0.9")
ax.set_axisbelow(True)
return fig, ax, bars
fig, ax, bars = draw_agreement(sat_counts, answered)
fig.savefig("figures/ch18/fig-18-12.png", dpi=300)
fig.savefig("figures/ch18/fig-18-12.pdf")
[label.get_text() for label in ax.get_xticklabels()]
bars.datavalues.tolist() == sat_counts["proportion"].to_list()
plt.close(fig)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
(492, 10, 1, 503)
shape: (5, 3)
┌───────────────────┬─────┬────────────┐
│ level ┆ n ┆ proportion │
│ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ f64 │
╞═══════════════════╪═════╪════════════╡
│ Strongly disagree ┆ 96 ┆ 0.195122 │
│ Disagree ┆ 65 ┆ 0.132114 │
│ Neutral ┆ 86 ┆ 0.174797 │
│ Agree ┆ 76 ┆ 0.154472 │
│ Strongly agree ┆ 169 ┆ 0.343496 │
└───────────────────┴─────┴────────────┘
['Strongly disagree', 'Disagree', 'Neutral', 'Agree', 'Strongly agree']
True
Figure 18.12. Ratings of life satisfaction on SAT_1, drawn with Matplotlib. Bar heights are percentages of the 492 forms with a rating. The labels give counts. Ten forms have a blank for this item and one records a refusal.
Of the 492 forms with a rating, 169 report Strongly agree, so the tallest bar reaches 34.3 percent. If the question were how often this answer appeared on any submitted form, the same 169 would be divided by 503, giving 33.6 percent.
Duration by gender
The same survey also records response duration. How does its distribution vary across gender categories? Each row is one response, so a participant who responded twice contributes both responses. A box plot compares each group’s median and spread without reducing its distribution to a mean.
The groups require consistent gender labels. With spaces trimmed and labels in lowercase, f and female both mean Female, m and male both mean Male, and other means Other.
In a box plot, the box extends from the first to the third quartile, with a line at the median. Its whiskers reach the most extreme observations within 1.5 interquartile ranges of the box edges. Values farther out appear as points, often called outliers.
For the constructed values 1, 2, 3, 4, 5, and 20, linear interpolation gives quartiles of 2.25 and 4.75 and a median of 3.5. The interquartile range is 2.5, giving limits of −1.5 and 8.5. The whiskers therefore end at 1 and 5, and 20 appears as a point. The whiskers end at observed values within the limits, not at the limits themselves.
In R, str_trim() removes surrounding spaces, str_to_lower() converts the labels to lowercase, and recode_values() assigns the gender categories. The resulting table, responses, has one duration per form. summarise() with .by = gender calculates each group’s count, mean, and quartiles. quantile(..., type = 7) uses linear interpolation, as does the box plot. Forms with no recorded gender have their own summary row.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
gender_dictionary <- tibble(
working = c("f", "female", "m", "male", "other"),
category = c("Female", "Female", "Male", "Male", "Other")
)
responses <- survey |>
select(ResponseId, ID, Gender, duration = `Duration (in seconds)`) |>
mutate(
gender = recode_values(
str_to_lower(str_trim(Gender)),
from = gender_dictionary$working,
to = gender_dictionary$category
)
)
duration_table <- responses |>
summarise(
n = n(),
mean = mean(duration),
q1 = quantile(duration, 0.25, type = 7, names = FALSE),
median = median(duration),
q3 = quantile(duration, 0.75, type = 7, names = FALSE),
.by = gender
) |>
arrange(gender)
duration_table
1
2
3
4
5
6
7
# A tibble: 4 × 6
gender n mean q1 median q3
<chr> <int> <dbl> <dbl> <dbl> <dbl>
1 Female 235 559. 416 519 656.
2 Male 252 569. 430. 545 688.
3 Other 13 505. 397 502 621
4 <NA> 3 492. 460 468 512.
The table includes three forms with no recorded gender. The plot uses the 500 forms in the named groups. Each horizontal label gives the number of responses behind that group’s box. geom_boxplot(coef = 1.5) computes the boxes and whiskers under the stated rule. The median lines are colored for visibility. layer_data() then returns the quartiles and whisker ends. Counting the values in outliers gives the number beyond the whiskers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
drawn <- responses |>
filter(!is.na(gender)) |>
mutate(label = paste0(gender, "\n(n = ", n(), ")"), .by = gender)
duration_plot <- ggplot(drawn, aes(x = label, y = duration)) +
geom_boxplot(coef = 1.5, median.colour = "#D55E00") +
labs(x = "Gender", y = "Response duration (seconds)") +
theme_minimal(base_size = 11)
ggsave(
"figures/ch18/fig-18-13.png", duration_plot,
width = 6.5, height = 4.2, units = "in", dpi = 300
)
ggsave(
"figures/ch18/fig-18-13.pdf", duration_plot,
width = 6.5, height = 4.2, units = "in"
)
layer_data(duration_plot) |>
mutate(beyond = lengths(outliers)) |>
select(x, lower, middle, upper, ymin, ymax, beyond)
1
2
3
4
x lower middle upper ymin ymax beyond
1 1 416.00 519 656.5 176 993 9
2 2 429.75 545 688.5 43 1033 5
3 3 397.00 502 621.0 275 834 0
Figure 18.13. Response duration by recorded gender for 500 forms, drawn with ggplot2. Boxes span the middle half, with a line at the median. Whiskers reach the most extreme durations within 1.5 interquartile ranges of the box edges. Points mark values beyond the whiskers. Three forms lack a recorded gender.
In Polars, replace_strict() applies the gender mapping. Polars’ quantile() with interpolation="linear" gives quartiles under the same convention as Matplotlib’s box plot. sort(nulls_last=True) puts the group without a gender last. drawn_table selects the named groups, and groups collects one duration array per group. zip() pairs each name and count to form its label.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
gender_dictionary = {
"f": "Female",
"female": "Female",
"m": "Male",
"male": "Male",
"other": "Other",
}
responses = survey.select(
"ResponseId",
"ID",
duration=pl.col("Duration (in seconds)"),
gender=pl.col("Gender")
.str.strip_chars(" ")
.str.to_lowercase()
.replace_strict(gender_dictionary, default=None),
)
duration_table = (
responses.group_by("gender")
.agg(
n=pl.len(),
mean=pl.col("duration").mean(),
q1=pl.col("duration").quantile(0.25, interpolation="linear"),
median=pl.col("duration").median(),
q3=pl.col("duration").quantile(0.75, interpolation="linear"),
)
.sort("gender", nulls_last=True)
)
duration_table
drawn_table = duration_table.drop_nulls("gender")
names = drawn_table["gender"].to_list()
groups = [
responses.filter(pl.col("gender") == name)["duration"].to_numpy() for name in names
]
labels = [name + "\n(n = " + str(n) + ")" for name, n in zip(names, drawn_table["n"])]
1
2
3
4
5
6
7
8
9
10
11
shape: (4, 6)
┌────────┬─────┬────────────┬────────┬────────┬───────┐
│ gender ┆ n ┆ mean ┆ q1 ┆ median ┆ q3 │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ u32 ┆ f64 ┆ f64 ┆ f64 ┆ f64 │
╞════════╪═════╪════════════╪════════╪════════╪═══════╡
│ Female ┆ 235 ┆ 558.86383 ┆ 416.0 ┆ 519.0 ┆ 656.5 │
│ Male ┆ 252 ┆ 568.531746 ┆ 429.75 ┆ 545.0 ┆ 688.5 │
│ Other ┆ 13 ┆ 505.153846 ┆ 397.0 ┆ 502.0 ┆ 621.0 │
│ null ┆ 3 ┆ 492.333333 ┆ 460.0 ┆ 468.0 ┆ 512.5 │
└────────┴─────┴────────────┴────────┴────────┴───────┘
Matplotlib’s ax.boxplot() draws one labeled box per duration array. whis=1.5 sets the 1.5-interquartile-range rule for whiskers, and medianprops sets the median line color. The returned dictionary gives the box and median coordinates and the outlier marks for comparison with duration_table.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def draw_boxes(groups, labels):
fig, ax = plt.subplots(figsize=(6.5, 4.2), layout="constrained")
parts = ax.boxplot(
groups, whis=1.5, tick_labels=labels, medianprops={"color": "#D55E00"}
)
ax.set_xlabel("Gender", fontsize=11)
ax.set_ylabel("Response duration (seconds)", fontsize=11)
ax.grid(axis="y", color="0.9")
ax.set_axisbelow(True)
return fig, parts
fig, parts = draw_boxes(groups, labels)
fig.savefig("figures/ch18/fig-18-14.png", dpi=300)
fig.savefig("figures/ch18/fig-18-14.pdf")
plt.close(fig)
pl.DataFrame(
{
"gender": names,
"q1": [box.get_ydata()[0] for box in parts["boxes"]],
"median": [line.get_ydata()[0] for line in parts["medians"]],
"q3": [box.get_ydata()[2] for box in parts["boxes"]],
"beyond": [len(points.get_ydata()) for points in parts["fliers"]],
}
)
1
2
3
4
5
6
7
8
9
10
shape: (3, 5)
┌────────┬────────┬────────┬───────┬────────┐
│ gender ┆ q1 ┆ median ┆ q3 ┆ beyond │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ f64 ┆ f64 ┆ f64 ┆ i64 │
╞════════╪════════╪════════╪═══════╪════════╡
│ Female ┆ 416.0 ┆ 519.0 ┆ 656.5 ┆ 9 │
│ Male ┆ 429.75 ┆ 545.0 ┆ 688.5 ┆ 5 │
│ Other ┆ 397.0 ┆ 502.0 ┆ 621.0 ┆ 0 │
└────────┴────────┴────────┴───────┴────────┘
Figure 18.14. Response duration by recorded gender for 500 forms, drawn with Matplotlib. Boxes span the middle half, with a line at the median. Whiskers reach the most extreme durations within 1.5 interquartile ranges of the box edges. Points mark values beyond the whiskers. Three forms lack a recorded gender.
A duration of 500 seconds falls inside all three boxes. Their medians are 519 seconds for Female, 545 for Male, and 502 for Other. The Other box summarizes 13 forms, compared with 235 for Female and 252 for Male. Nine durations fall beyond the whiskers in the Female group and five in the Male group. Their distance from the box alone cannot tell us whether a duration was recorded in error.
18.4 Showing repeated measurements and gaps
If a person has depression scores at waves 1 and 3 but misses wave 2, should a line connect those scores? Each point marks one person’s observed total at one wave. A line joins scores from the same person at adjacent scheduled waves only, so the two scores on either side of a missed visit appear as separate points.
Participants with IDs from 0001 to 0300 entered the panel at wave 1, and those from 0301 to 0315 entered at wave 2. A person is eligible from their entry wave onward. A recorded date indicates a visit, even if the score is missing. In the three examples, 0006 has scores at all three waves, 0062 missed wave 2, and 0301 entered at wave 2.
pivot_longer() creates one row for each person at each wave, including waves with a blank date or score. It splits names such as dep_w2 into a measure and a wave label, and parse_number() reads the wave number. eligible tests whether that wave is at or after enrollment. attended tests for a date and observed for a depression total.
An inner_join() with cases selects the three participants. After sorting by ID and wave, lead() within each ID finds the next wave and score. A pair becomes a segment only if its waves are adjacent and both have scores. This produces a separate table of connections without removing isolated scores from trajectories.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
later_entrants <- sprintf("%04d", 301:315)
panel_long <- panel |>
select(id, starts_with(c("date_", "dep_"))) |>
pivot_longer(cols = -id, names_to = c(".value", "wave"), names_sep = "_") |>
mutate(
wave = parse_number(wave),
entry_wave = if_else(id %in% later_entrants, 2, 1),
eligible = wave >= entry_wave,
attended = !is.na(date),
observed = !is.na(dep)
)
cases <- tibble(
id = c("0006", "0062", "0301"),
case = c("Complete (0006)", "Missed wave 2 (0062)", "Entered at wave 2 (0301)")
) |>
mutate(case = factor(case, levels = case))
trajectories <- panel_long |>
inner_join(cases, by = "id") |>
arrange(id, wave)
select(trajectories, id, wave, eligible, attended, observed, dep)
segments <- trajectories |>
mutate(next_wave = lead(wave), next_dep = lead(dep), .by = id) |>
filter(next_wave == wave + 1 & !is.na(dep) & !is.na(next_dep))
select(segments, id, wave, dep, next_wave, next_dep)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# A tibble: 9 × 6
id wave eligible attended observed dep
<chr> <dbl> <lgl> <lgl> <lgl> <int>
1 0006 1 TRUE TRUE TRUE 2
2 0006 2 TRUE TRUE TRUE 12
3 0006 3 TRUE TRUE TRUE 14
4 0062 1 TRUE TRUE TRUE 6
5 0062 2 TRUE FALSE FALSE NA
6 0062 3 TRUE TRUE TRUE 9
7 0301 1 FALSE FALSE FALSE NA
8 0301 2 TRUE TRUE TRUE 13
9 0301 3 TRUE TRUE TRUE 9
# A tibble: 3 × 5
id wave dep next_wave next_dep
<chr> <dbl> <int> <dbl> <int>
1 0006 1 2 2 12
2 0006 2 12 3 14
3 0301 2 13 3 9
The table gives 0006 two segments and 0301 one. Participant 0062 has no pair of adjacent observed totals. geom_segment() draws a line between the start and end in each segment row. A separate geom_point() layer draws every observed total, including those without a segment. facet_wrap() places each person in a separate panel.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
trajectory_plot <- ggplot(mapping = aes(x = wave, y = dep)) +
geom_segment(
data = segments,
aes(xend = next_wave, yend = next_dep),
colour = "#0072B2"
) +
geom_point(data = filter(trajectories, observed), colour = "#0072B2", size = 2.5) +
facet_wrap(vars(case)) +
scale_x_continuous(breaks = 1:3, limits = c(0.8, 3.2)) +
scale_y_continuous(limits = c(0, 18)) +
labs(x = "Wave", y = "Depression total (points)") +
theme_minimal(base_size = 11)
ggsave(
"figures/ch18/fig-18-15.png", trajectory_plot,
width = 6.5, height = 4.2, units = "in", dpi = 300
)
ggsave(
"figures/ch18/fig-18-15.pdf", trajectory_plot,
width = 6.5, height = 4.2, units = "in"
)
c(
segments = nrow(layer_data(trajectory_plot, i = 1)),
points = nrow(layer_data(trajectory_plot, i = 2))
)
1
2
segments points
3 7
Figure 18.15. Depression scores by wave for three participants, drawn with ggplot2. A line joins two scores only at adjacent waves for the same person. The two points for 0062 are separate because this participant missed wave 2.
For 0006, the segments connect totals of 2, 12, and 14. For 0062, points at 6 and 9 appear on either side of the missed second wave. Drawing the points separately matters here because this participant contributes observations even though the segment table has no row for them.
In Polars, panel_wave() selects each person’s ID, date, and depression total for one wave. pl.concat() stacks all three wave tables. The expression later_entry tests the numeric ID against the range from 301 to 315. The first with_columns() records entry wave, attendance, and score availability. The second uses entry_wave to determine eligibility.
After joining the three cases and sorting by person and wave, shift(-1).over("id") finds the next wave and score for the same person. A segment requires consecutive wave numbers and a score at both ends. The filtered segments table describes the connections; trajectories still provides every observed score, including those without a connection.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def panel_wave(wave):
return panel.select(
"id",
wave=pl.lit(wave),
date=pl.col("date_w" + str(wave)),
dep=pl.col("dep_w" + str(wave)),
)
later_entry = pl.col("id").cast(pl.Int64).is_between(301, 315)
panel_long = pl.concat(
[panel_wave(1), panel_wave(2), panel_wave(3)], how="vertical"
).with_columns(
entry_wave=pl.when(later_entry).then(2).otherwise(1),
attended=pl.col("date").is_not_null(),
observed=pl.col("dep").is_not_null(),
).with_columns(eligible=pl.col("wave") >= pl.col("entry_wave"))
cases = pl.DataFrame(
{
"id": ["0006", "0062", "0301"],
"case": ["Complete (0006)", "Missed wave 2 (0062)", "Entered at wave 2 (0301)"],
}
)
trajectories = panel_long.join(cases, on="id").sort("id", "wave")
trajectories.select("id", "wave", "eligible", "attended", "observed", "dep")
segments = trajectories.with_columns(
next_wave=pl.col("wave").shift(-1).over("id"),
next_dep=pl.col("dep").shift(-1).over("id"),
).filter(
(pl.col("next_wave") == pl.col("wave") + 1)
& pl.col("dep").is_not_null()
& pl.col("next_dep").is_not_null()
)
segments.select("id", "wave", "dep", "next_wave", "next_dep")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
shape: (9, 6)
┌──────┬──────┬──────────┬──────────┬──────────┬──────┐
│ id ┆ wave ┆ eligible ┆ attended ┆ observed ┆ dep │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i32 ┆ bool ┆ bool ┆ bool ┆ i64 │
╞══════╪══════╪══════════╪══════════╪══════════╪══════╡
│ 0006 ┆ 1 ┆ true ┆ true ┆ true ┆ 2 │
│ 0006 ┆ 2 ┆ true ┆ true ┆ true ┆ 12 │
│ 0006 ┆ 3 ┆ true ┆ true ┆ true ┆ 14 │
│ 0062 ┆ 1 ┆ true ┆ true ┆ true ┆ 6 │
│ 0062 ┆ 2 ┆ true ┆ false ┆ false ┆ null │
│ 0062 ┆ 3 ┆ true ┆ true ┆ true ┆ 9 │
│ 0301 ┆ 1 ┆ false ┆ false ┆ false ┆ null │
│ 0301 ┆ 2 ┆ true ┆ true ┆ true ┆ 13 │
│ 0301 ┆ 3 ┆ true ┆ true ┆ true ┆ 9 │
└──────┴──────┴──────────┴──────────┴──────────┴──────┘
shape: (3, 5)
┌──────┬──────┬─────┬───────────┬──────────┐
│ id ┆ wave ┆ dep ┆ next_wave ┆ next_dep │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i32 ┆ i64 ┆ i32 ┆ i64 │
╞══════╪══════╪═════╪═══════════╪══════════╡
│ 0006 ┆ 1 ┆ 2 ┆ 2 ┆ 12 │
│ 0006 ┆ 2 ┆ 12 ┆ 3 ┆ 14 │
│ 0301 ┆ 2 ┆ 13 ┆ 3 ┆ 9 │
└──────┴──────┴─────┴───────────┴──────────┘
draw_trajectories() creates three axes sharing the depression scale. zip() pairs each person with a plotting area. For each segment, ax.plot() joins its two endpoints. Then ax.scatter() adds the observed totals, with zorder=3 placing points above lines. The final checks count the lines and points in each plotting area.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
def draw_trajectories(trajectories, segments, cases):
fig, axes = plt.subplots(
1, 3, figsize=(6.5, 4.2), sharey=True, layout="constrained"
)
for ax, person, case in zip(axes, cases["id"], cases["case"]):
lines = segments.filter(pl.col("id") == person)
for x0, y0, x1, y1 in zip(
lines["wave"], lines["dep"], lines["next_wave"], lines["next_dep"]
):
ax.plot([x0, x1], [y0, y1], color="#0072B2")
points = trajectories.filter((pl.col("id") == person) & pl.col("observed"))
ax.scatter(points["wave"], points["dep"], color="#0072B2", zorder=3)
ax.set_title(case, fontsize=10)
ax.set_xticks([1, 2, 3])
ax.set_xlim(0.8, 3.2)
ax.set_ylim(0, 18)
ax.set_xlabel("Wave", fontsize=11)
ax.grid(color="0.9")
ax.set_axisbelow(True)
axes[0].set_ylabel("Depression total (points)", fontsize=11)
return fig, axes
fig, axes = draw_trajectories(trajectories, segments, cases)
fig.savefig("figures/ch18/fig-18-16.png", dpi=300)
fig.savefig("figures/ch18/fig-18-16.pdf")
[len(ax.lines) for ax in axes]
[len(ax.collections[0].get_offsets()) for ax in axes]
plt.close(fig)
1
2
[2, 0, 1]
[3, 2, 2]
Figure 18.16. Depression scores by wave for three participants, drawn with Matplotlib. A line joins two scores only at adjacent waves for the same person. The two points for 0062 are separate because this participant missed wave 2.
For 0062, the middle entries give zero lines and two points. The scores of 6 and 9 are visible at waves 1 and 3, with a gap at the missed visit.
There is no point for 0301 at wave 1 or for 0062 at wave 2. Neither occasion has a date or a score. Participant 0301 had yet to enroll, so eligible is false. Participant 0062 was eligible, so the missing date indicates a missed visit. A person can attend without a score, so the first plotted point alone cannot tell us when they enrolled.
Means by wave
Each point in the three individual panels represents one person’s score. What goes into a point showing the mean for a whole wave? Summing eligible, attended, and observed by wave counts the people enrolled by then, those who attended, and those with a score. At wave 1, 300 people attended and 276 had a depression total.
In R, mean(dep, na.rm = TRUE) averages those 276 scores. The count of observed totals supplies the label n = 276, identifying how many people contribute to the first mean.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
wave_summary <- panel_long |>
summarise(
eligible = sum(eligible),
attended = sum(attended),
observed = sum(observed),
mean = mean(dep, na.rm = TRUE),
.by = wave
)
wave_summary
mean_plot <- ggplot(wave_summary, aes(x = wave, y = mean)) +
geom_point(colour = "#0072B2", size = 3) +
geom_text(aes(label = paste0("n = ", observed)), vjust = -1.2, size = 3.5) +
scale_x_continuous(breaks = 1:3, limits = c(0.8, 3.2)) +
scale_y_continuous(limits = c(0, 18)) +
labs(x = "Wave", y = "Mean of observed depression totals (points)") +
theme_minimal(base_size = 11)
ggsave(
"figures/ch18/fig-18-17.png", mean_plot,
width = 6.5, height = 4.2, units = "in", dpi = 300
)
ggsave(
"figures/ch18/fig-18-17.pdf", mean_plot,
width = 6.5, height = 4.2, units = "in"
)
1
2
3
4
5
6
# A tibble: 3 × 5
wave eligible attended observed mean
<dbl> <int> <int> <int> <dbl>
1 1 300 300 276 6.64
2 2 315 273 259 6.76
3 3 315 254 237 7.01
Figure 18.17. Mean depression score at each wave, drawn with ggplot2. The labels show that 276 people contributed a score at wave 1, 259 at wave 2, and 237 at wave 3.
In Python, wave_summary groups all rows of panel_long by wave. sum() counts true values in each logical column, and mean() skips null totals. draw_means() plots one point per wave. ax.annotate() places the observed-count label above its mean. The setting textcoords="offset points" measures the displacement in type points, a printing unit, rather than score units.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
wave_summary = (
panel_long.group_by("wave")
.agg(
eligible=pl.col("eligible").sum(),
attended=pl.col("attended").sum(),
observed=pl.col("observed").sum(),
mean=pl.col("dep").mean(),
)
.sort("wave")
)
wave_summary
def draw_means(wave_summary):
fig, ax = plt.subplots(figsize=(6.5, 4.2), layout="constrained")
ax.scatter(wave_summary["wave"], wave_summary["mean"], color="#0072B2", s=50)
for wave, mean, n in zip(
wave_summary["wave"], wave_summary["mean"], wave_summary["observed"]
):
ax.annotate(
"n = " + str(n), (wave, mean), xytext=(0, 10),
textcoords="offset points", ha="center",
)
ax.set_xticks([1, 2, 3])
ax.set_xlim(0.8, 3.2)
ax.set_ylim(0, 18)
ax.set_xlabel("Wave", fontsize=11)
ax.set_ylabel("Mean of observed depression totals (points)", fontsize=11)
ax.grid(color="0.9")
ax.set_axisbelow(True)
return fig, ax
fig, ax = draw_means(wave_summary)
fig.savefig("figures/ch18/fig-18-18.png", dpi=300)
fig.savefig("figures/ch18/fig-18-18.pdf")
[text.get_text() for text in ax.texts]
plt.close(fig)
1
2
3
4
5
6
7
8
9
10
11
shape: (3, 5)
┌──────┬──────────┬──────────┬──────────┬──────────┐
│ wave ┆ eligible ┆ attended ┆ observed ┆ mean │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ i32 ┆ u32 ┆ u32 ┆ u32 ┆ f64 │
╞══════╪══════════╪══════════╪══════════╪══════════╡
│ 1 ┆ 300 ┆ 300 ┆ 276 ┆ 6.641304 │
│ 2 ┆ 315 ┆ 273 ┆ 259 ┆ 6.764479 │
│ 3 ┆ 315 ┆ 254 ┆ 237 ┆ 7.012658 │
└──────┴──────────┴──────────┴──────────┴──────────┘
['n = 276', 'n = 259', 'n = 237']
Figure 18.18. Mean depression score at each wave, drawn with Matplotlib. The labels show that 276 people contributed a score at wave 1, 259 at wave 2, and 237 at wave 3.
The mean rises from 6.64 points at wave 1 to 7.01 at wave 3. The means are plotted as separate points because different people can contribute scores at each wave. Some people joined at wave 2, and some attended a visit without a score. To find the average change for the same people, we would need to compare their scores in pairs.

















