---
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 >}}
# 演習と、図のチェックリスト {#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
```
この章のコードセルは自動では実行されません。**空欄(`___`)を埋めて「Run Code」** を押してください。好きな言語のタブで取り組み、余裕があればもう一方の言語でも同じ図を作ってみてください。解答例は各問の下に折りたたんであります。
## 図のチェックリスト
| # | 確かめること | 章 |
|---|---|---|
| 1 | 軸のラベルに **量と単位** があるか(「体重 (g)」) | 1 |
| 2 | 色は **意味のある対応づけ** か。色覚の多様性・白黒印刷でも区別できるか。同じ群は **全部の図で同じ色** か | 2 |
| 3 | 点が重なっていないか(透明度・区画・等高線) | 2 |
| 4 | カテゴリの **順番と名前** を意図して決めたか | 3 |
| 5 | 分布を隠していないか(箱ひげ図だけ・棒グラフ+誤差棒だけ → 点を見せる) | 4 |
| 6 | 誤差棒が **SD・SE・CI のどれか** を書いたか | 4 |
| 7 | 有意差の記号は、**検定・補正・記号の意味** を書いたか。比べる組み合わせは事前に決めたか | 5 |
| 8 | 回帰直線は、**群を分けると向きが変わらないか** 確かめたか。帯が **信頼区間か予測区間か** を書いたか | 6 |
| 9 | **実際の大きさ(mm)と文字の大きさ(pt)** で作ったか。ベクター形式で保存したか | 7 |
| 10 | 複数パネルに **A, B, C** のラベルがあり、軸・凡例がそろっているか | 8 |
| 11 | 軸の範囲を絞るとき、**データを捨てていないか**(`coord_cartesian()`) | 9 |
| 12 | 除いたデータ(欠測・範囲外)と **人数** を、図の説明に書いたか | 1, 9 |
## 演習 1:糖尿病の有無と収縮期血圧(男女別)
NHANES で、**性別ごとに、糖尿病の有無で収縮期血圧(`BPSysAve`)を比べる** 図を作ります。
- 箱ひげ図に点を重ねる(点は 1 群 150 人だけ表示する)
- 男女それぞれで、糖尿病あり・なしを **Welch の t 検定** で比べ、線とアスタリスクを描く
::: {.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) # 表示する点
res <- nh |> group_by(Gender) |>
summarise(p = t.test(BPSysAve ~ Diabetes)$p.value, y = max(BPSysAve)) |>
mutate(記号 = cut(p, c(-Inf, 1e-4, 1e-3, 0.01, 0.05, Inf), c("****", "***", "**", "*", "ns"), right = FALSE),
x = as.integer(factor(Gender)))
off <- ___ # dodge の幅 0.75 で 2 群のずれ
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 = 記号), vjust = -0.2, inherit.aes = FALSE) +
labs(x = NULL, y = "収縮期血圧 (mmHg)", fill = "糖尿病", colour = "糖尿病")
```
## 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 = ___ # seaborn の hue 2 群のずれ
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="収縮期血圧 (mmHg)")
ax.legend(title="糖尿病")
plt.show()
```
:::
::: {.callout-tip collapse="true"}
## 解答
- R:`off <- 0.75 / 4`(dodge の幅 0.75 を 2 群で分けるので、中心から ±0.1875)
- Python:`off = 0.2`(seaborn の既定の幅 0.8 を 2 群で分けるので ±0.2)
男女とも、糖尿病ありの人のほうが収縮期血圧が高く、p は非常に小さくなります(****)。ただし、糖尿病ありの人は **年齢が高い** ので、この差には年齢の交絡が含まれます([交絡ハンズオン](/study/confounding_hands_on/))。図の説明には、各群の人数と、年齢で調整していないことも書きます。
:::
## 演習 2:年齢とコレステロール、男女別の回帰式
NHANES で、**年齢と総コレステロール(`TotChol`, mmol/L)** の散布図に、男女別の回帰直線と式を描きます。式はパネルの **左上** に、男女 1 行ずつ、線と同じ色で置きます。
::: {.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_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 * (行 - 1)),
hjust = -0.05, show.legend = FALSE) +
scale_colour_manual(values = cols) +
labs(x = "年齢", y = "総コレステロール (mmol/L)", colour = "性別")
```
## 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="年齢", ylabel="総コレステロール (mmol/L)")
plt.show()
```
:::
::: {.callout-tip collapse="true"}
## 解答
- R:`x = -Inf, y = Inf`(パネルの左上の角)
- Python:`transform=ax.transAxes`(パネルの座標)
R² はどちらも小さく、直線ではあまり説明できていません。散布図を見ると、特に女性では 60 歳ごろまでコレステロールが上がり、その後は下がる **曲線的な関係** です。`geom_smooth()` の `method` を `"loess"` にしたり、`formula = y ~ splines::ns(x, 3)` にしたりして、直線の仮定を確かめてみましょう。
:::
## 演習 3:論文用の 2 パネルの図
ペンギンのデータで、次の 2 パネルの図を **幅 170 mm・高さ 70 mm、文字 8 pt** で作ります。
- **A**:ひれの長さと体重の散布図(種で色分け)
- **B**:種ごとの体重の箱ひげ図+点
- 凡例は 1 つにまとめる。A, B のラベルをつける
::: {.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 = "ひれの長さ (mm)", y = "体重 (g)", colour = "種")
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 = "体重 (g)", colour = "種")
(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="ひれの長さ (mm)", ylabel="体重 (g)"); b.set(xlabel="", ylabel="体重 (g)")
b.legend(title="種", 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"}
## 解答
- R:`guides = "collect"`, `tag_levels = "A"`, `base_size = 8`(`fig-width` 6.7 インチ ≒ 170 mm、`fig-height` 2.76 インチ ≒ 70 mm)
- Python:`"font.size": 8`, `figsize=(170 * mm, 70 * mm)`
保存するときは、R なら `ggsave("fig.pdf", width = 170, height = 70, units = "mm", device = cairo_pdf)`、Python なら `fig.savefig("fig.pdf")`(`pdf.fonttype = 42`)です。
patchwork の `&` は、**すべてのパネル** に同じ設定(配色・テーマ)を適用します(`+` は最後のパネルだけ)。
:::
## おわりに
ggplot2 と matplotlib / seaborn は、書き方は違っても、
- **データをどの見た目に対応づけるか**(位置・色・形・大きさ)
- **描く前に何を計算するか**(数える・要約する・直線を当てはめる)
- **どの座標で位置を決めるか**(データ・パネル・図全体)
- **どの大きさで、どの形式で出すか**
という同じことを決めています。この 4 つを意識すれば、どちらの言語でも、「思いどおりの図」と「誤解されない図」を作れるようになります。