---
webr:
packages: [dplyr, ggplot2, patchwork]
resources: [R/setup.R, py/setup.py, data/penguins.csv, data/nhanes_adults.csv, fonts/NotoSansJP-Regular.ttf, fonts/NotoSansJP-Bold.ttf]
cell-options:
autorun: false
pyodide:
packages: [pandas, matplotlib, seaborn, scipy, statsmodels]
cell-options:
autorun: false
---
{{< include ./_extensions/r-wasm/live/_knitr.qmd >}}
# Exercises and a figure checklist {#sec-exercises}
```{webr}
#| include: false
#| autorun: true
source("R/setup.R")
library(patchwork)
```
```{pyodide}
#| include: false
#| autorun: true
exec(open("py/setup.py").read())
from scipy import stats
from statsmodels.stats.multitest import multipletests
```
The code cells in this chapter are not run automatically. **Fill in the blanks (`___`) and press "Run Code"**. Work in the tab of whichever language you prefer, and if you have time, make the same figure in the other language too. Sample answers are collapsed below each exercise.
## Figure checklist
| # | What to check | Chapter |
|---|---|---|
| 1 | Do the axis labels have **a quantity and unit** ("Body mass (g)")? | 1 |
| 2 | Is colour **a meaningful mapping**? Is it distinguishable for diverse colour vision and in black-and-white print? Is the same group **the same colour in every figure**? | 2 |
| 3 | Are points overplotted (transparency, cells, contours)? | 2 |
| 4 | Did you deliberately decide the **order and names** of categories? | 3 |
| 5 | Are you hiding the distribution (box plot only, bar chart + error bars only → show the points)? | 4 |
| 6 | Did you state **whether the error bars are SD, SE or CI**? | 4 |
| 7 | For significance symbols, did you state **the test, the correction and what the symbols mean**? Were the pairs to compare decided in advance? | 5 |
| 8 | For regression lines, did you check **whether the direction changes when groups are separated**? Did you state whether the band is **a confidence interval or a prediction interval**? | 6 |
| 9 | Did you make it at **the actual size (mm) and text size (pt)**? Did you save in a vector format? | 7 |
| 10 | Do the multiple panels have **A, B, C** labels, with aligned axes and legends? | 8 |
| 11 | When narrowing the axis range, are you **discarding data** (`coord_cartesian()`)? | 9 |
| 12 | Did you state the excluded data (missing, out of range) and **the sample sizes** in the figure's description? | 1, 9 |
## Exercise 1: diabetes and systolic blood pressure (by sex)
Using NHANES, make a figure that **compares systolic blood pressure (`BPSysAve`) by diabetes status, separately for each sex**.
- Overlay points on box plots (show only 150 points per group)
- Within each sex, compare with vs without diabetes using **Welch's t-test**, and draw brackets and asterisks
::: {.panel-tabset group="lang"}
## R (ggplot2)
```{webr}
nh <- nhanes |> filter(!is.na(BPSysAve), !is.na(Diabetes))
set.seed(1)
pts <- nh |> group_by(Gender, Diabetes) |> slice_sample(n = 150) # points to display
res <- nh |> group_by(Gender) |>
summarise(p = t.test(BPSysAve ~ Diabetes)$p.value, y = max(BPSysAve)) |>
mutate(symbol = cut(p, c(-Inf, 1e-4, 1e-3, 0.01, 0.05, Inf), c("****", "***", "**", "*", "ns"), right = FALSE),
x = as.integer(factor(Gender)))
off <- ___ # offset of 2 groups with a dodge width of 0.75
ggplot(nh, aes(Gender, BPSysAve, fill = Diabetes)) +
geom_boxplot(outlier.shape = NA, position = position_dodge(0.75), width = 0.6, alpha = 0.6) +
geom_point(data = pts, aes(colour = Diabetes), size = 0.6, alpha = 0.4,
position = position_jitterdodge(jitter.width = 0.15, dodge.width = 0.75, seed = 1)) +
geom_segment(data = res, aes(x = x - off, xend = x + off, y = y + 5, yend = y + 5), inherit.aes = FALSE) +
geom_text(data = res, aes(x = x, y = y + 5, label = symbol), vjust = -0.2, inherit.aes = FALSE) +
labs(x = NULL, y = "Systolic blood pressure (mmHg)", fill = "Diabetes", colour = "Diabetes")
```
## Python (seaborn / matplotlib)
```{pyodide}
nh = nhanes.dropna(subset=["BPSysAve", "Diabetes"])
pts = nh.groupby(["Gender", "Diabetes"], group_keys=False).sample(150, random_state=1)
order = ["female", "male"]
fig, ax = plt.subplots()
sns.boxplot(data=nh, x="Gender", y="BPSysAve", hue="Diabetes", order=order, showfliers=False, boxprops={"alpha": 0.6}, ax=ax)
np.random.seed(1)
sns.stripplot(data=pts, x="Gender", y="BPSysAve", hue="Diabetes", order=order, dodge=True, size=2, alpha=0.4,
palette=["0.3", "0.3"], legend=False, ax=ax)
off = ___ # offset of 2 hue groups in seaborn
for i, g in enumerate(order):
d = nh[nh["Gender"] == g]
p = stats.ttest_ind(d.loc[d["Diabetes"] == "No", "BPSysAve"], d.loc[d["Diabetes"] == "Yes", "BPSysAve"], equal_var=False).pvalue
star = next((s for t, s in [(1e-4, "****"), (1e-3, "***"), (0.01, "**"), (0.05, "*")] if p < t), "ns")
y = d["BPSysAve"].max() + 5
ax.plot([i - off, i + off], [y, y], color="black", lw=1)
ax.text(i, y, star, ha="center", va="bottom")
ax.set(xlabel="", ylabel="Systolic blood pressure (mmHg)")
ax.legend(title="Diabetes")
plt.show()
```
:::
::: {.callout-tip collapse="true"}
## Answer
- R: `off <- 0.75 / 4` (the dodge width of 0.75 is split between 2 groups, so ±0.1875 from the centre)
- Python: `off = 0.2` (seaborn's default width of 0.8 is split between 2 groups, so ±0.2)
For both sexes, people with diabetes have higher systolic blood pressure, with very small p-values (\*\*\*\*). However, people with diabetes are **older**, so this difference includes confounding by age ([confounding hands-on](https://lab.nghmst.com/study/en/confounding_hands_on/)). In the figure's description, also state the size of each group and that the comparison is not adjusted for age.
:::
## Exercise 2: age and cholesterol, regression equations by sex
Using NHANES, draw regression lines and equations by sex on a scatter plot of **age and total cholesterol (`TotChol`, mmol/L)**. Place the equations at the **top left** of the panel, one line per sex, in the same colour as the lines.
::: {.panel-tabset group="lang"}
## R (ggplot2)
```{webr}
nc <- nhanes |> filter(!is.na(TotChol), !is.na(Age))
cols <- c(female = "#D55E00", male = "#0072B2")
eqs <- nc |> group_by(Gender) |>
summarise(fit = list(lm(TotChol ~ Age))) |>
mutate(b1 = sapply(fit, \(f) coef(f)[2]), b0 = sapply(fit, \(f) coef(f)[1]),
r2 = sapply(fit, \(f) summary(f)$r.squared),
label = sprintf("%s: y = %.4fx + %.2f, R² = %.3f", Gender, b1, b0, r2),
row = row_number())
ggplot(nc, aes(Age, TotChol, colour = Gender)) +
geom_point(size = 0.4, alpha = 0.1) +
geom_smooth(method = "lm", formula = y ~ x) +
geom_text(data = eqs, aes(x = ___, y = ___, label = label, vjust = 1.3 + 1.5 * (row - 1)),
hjust = -0.05, show.legend = FALSE) +
scale_colour_manual(values = cols) +
labs(x = "Age", y = "Total cholesterol (mmol/L)", colour = "Sex")
```
## Python (seaborn / matplotlib)
```{pyodide}
nc = nhanes.dropna(subset=["TotChol", "Age"])
cols = {"female": "#D55E00", "male": "#0072B2"}
fig, ax = plt.subplots()
for i, (g, d) in enumerate(nc.groupby("Gender")):
r = stats.linregress(d["Age"], d["TotChol"])
sns.regplot(data=d, x="Age", y="TotChol", color=cols[g], scatter_kws={"s": 2, "alpha": 0.1}, seed=1, ax=ax, label=g)
ax.text(0.02, 0.97 - 0.07 * i, f"{g}: y = {r.slope:.4f}x + {r.intercept:.2f}, R² = {r.rvalue**2:.3f}",
transform=___, color=cols[g], ha="left", va="top")
ax.set(xlabel="Age", ylabel="Total cholesterol (mmol/L)")
plt.show()
```
:::
::: {.callout-tip collapse="true"}
## Answer
- R: `x = -Inf, y = Inf` (the top-left corner of the panel)
- Python: `transform=ax.transAxes` (panel coordinates)
R² is small for both, so a straight line explains little. Looking at the scatter plot, the relationship is **curved**, especially in women: cholesterol rises until about age 60 and then falls. Try setting `geom_smooth()`'s `method` to `"loess"` or using `formula = y ~ splines::ns(x, 3)` to check the straight-line assumption.
:::
## Exercise 3: a two-panel figure for a paper
Using the penguin data, make the following two-panel figure at **170 mm wide, 70 mm high, with 8 pt text**.
- **A**: scatter plot of flipper length and body mass (coloured by species)
- **B**: box plot + points of body mass by species
- Merge the legends into one. Add A and B labels
::: {.panel-tabset group="lang"}
## R (ggplot2)
```{webr}
#| fig-width: 6.7
#| fig-height: 2.76
cols <- c(Adelie = "#E69F00", Chinstrap = "#56B4E9", Gentoo = "#009E73")
pp <- penguins |> filter(!is.na(body_mass_g))
pa <- ggplot(pp, aes(flipper_length_mm, body_mass_g, colour = species)) + geom_point(size = 0.8, alpha = 0.7) +
labs(x = "Flipper length (mm)", y = "Body mass (g)", colour = "Species")
pb <- ggplot(pp, aes(species, body_mass_g, colour = species)) +
geom_boxplot(outlier.shape = NA, width = 0.5) +
geom_point(position = position_jitter(width = 0.12, height = 0, seed = 1), size = 0.6, alpha = 0.4) +
labs(x = NULL, y = "Body mass (g)", colour = "Species")
(pa + pb) + plot_layout(widths = c(3, 2), guides = ___) + plot_annotation(tag_levels = ___) &
scale_colour_manual(values = cols) & theme_classic(base_size = ___)
```
## Python (seaborn / matplotlib)
```{pyodide}
mm = 1 / 25.4
cols = {"Adelie": "#E69F00", "Chinstrap": "#56B4E9", "Gentoo": "#009E73"}
pp = penguins.dropna(subset=["body_mass_g"])
with plt.rc_context({"font.size": ___, "axes.spines.top": False, "axes.spines.right": False, "axes.grid": False}):
fig, (a, b) = plt.subplots(1, 2, figsize=(___ * mm, ___ * mm), width_ratios=[3, 2], layout="constrained")
sns.scatterplot(data=pp, x="flipper_length_mm", y="body_mass_g", hue="species", palette=cols, s=6, linewidth=0, ax=a, legend=False)
sns.boxplot(data=pp, x="species", y="body_mass_g", hue="species", palette=cols, showfliers=False, width=0.5, fill=False, ax=b, legend=False)
np.random.seed(1)
sns.stripplot(data=pp, x="species", y="body_mass_g", hue="species", palette=cols, size=1.8, alpha=0.4, jitter=0.12, ax=b)
a.set(xlabel="Flipper length (mm)", ylabel="Body mass (g)"); b.set(xlabel="", ylabel="Body mass (g)")
b.legend(title="Species", frameon=False, loc="upper left", bbox_to_anchor=(1, 1))
for lab, ax in zip("AB", (a, b)):
ax.text(-0.15, 1.02, lab, transform=ax.transAxes, fontweight="bold", fontsize=10, va="bottom")
plt.show()
```
:::
::: {.callout-tip collapse="true"}
## Answer
- R: `guides = "collect"`, `tag_levels = "A"`, `base_size = 8` (`fig-width` 6.7 inches ≈ 170 mm, `fig-height` 2.76 inches ≈ 70 mm)
- Python: `"font.size": 8`, `figsize=(170 * mm, 70 * mm)`
To save, use `ggsave("fig.pdf", width = 170, height = 70, units = "mm", device = cairo_pdf)` in R and `fig.savefig("fig.pdf")` (with `pdf.fonttype = 42`) in Python.
patchwork's `&` applies the same settings (colours, theme) to **all panels** (`+` applies only to the last panel).
:::
## Closing remarks
ggplot2 and matplotlib / seaborn are written differently, but both decide the same things:
- **which visual properties to map the data to** (position, colour, shape, size)
- **what to compute before drawing** (counting, summarising, fitting a line)
- **which coordinates determine positions** (data, panel, whole figure)
- **at what size and in what format to output**
If you keep these four in mind, you will be able to make "the figure you want" and "a figure that can't be misread" in either language.