---
webr:
packages: [dplyr, ggplot2, ggsignif]
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: true
pyodide:
packages: [pandas, matplotlib, seaborn, scipy, statsmodels]
cell-options:
autorun: true
---
{{< include ./_extensions/r-wasm/live/_knitr.qmd >}}
# 有意差のアスタリスクと線 {#sec-significance}
```{webr}
#| include: false
source("R/setup.R")
peng <- penguins |> filter(!is.na(sex)) |>
mutate(種 = factor(species, c("Adelie", "Chinstrap", "Gentoo"), c("アデリー", "ヒゲ", "ジェンツー")),
性別 = factor(sex, c("female", "male"), c("メス", "オス")))
```
```{pyodide}
#| include: false
exec(open("py/setup.py").read())
from scipy import stats
from statsmodels.stats.multitest import multipletests
peng = penguins.dropna(subset=["sex"]).copy()
peng["種"] = pd.Categorical(peng["species"].map({"Adelie": "アデリー", "Chinstrap": "ヒゲ", "Gentoo": "ジェンツー"}),
categories=["アデリー", "ヒゲ", "ジェンツー"])
peng["性別"] = pd.Categorical(peng["sex"].map({"female": "メス", "male": "オス"}), categories=["メス", "オス"])
```
群を比べた図に、**検定の結果を線とアスタリスク(*)で描き込む** 形は、生命科学・医学の論文でとてもよく見かけます。
この章では、**検定を自分で行い、その結果を自分で描く** 方法を練習します。便利なパッケージもありますが、何を描いているかを自分で制御できることが大切です。
## 手順
1. **何と何を比べるか** を決める(すべての組み合わせか、対照群とだけか)
2. 検定を行い、**多重比較の補正** をする
3. p 値を、アスタリスクなどの記号に変換する
4. 線(ブラケット)と記号を、**データに重ならない高さ** に描く
## 1–2. 検定と多重比較の補正
3 種の体重を、2 種ずつ比べます(3 通り)。後で線を重ならないように積み上げるため、**隣どうしの比較(短い線)を先に、離れた群の比較(長い線)を後に** 並べておきます。ここでは、等分散を仮定しない t 検定(Welch)を行い、**Holm の方法** で補正します。
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
pairs <- list(c("アデリー", "ヒゲ"), c("ヒゲ", "ジェンツー"), c("アデリー", "ジェンツー")) # 短い線を先(下)に、長い線を後(上)に
res <- do.call(rbind, lapply(pairs, function(pr) {
x <- peng$body_mass_g[peng$種 == pr[1]]; y <- peng$body_mass_g[peng$種 == pr[2]]
data.frame(群1 = pr[1], 群2 = pr[2], 差 = mean(y) - mean(x), p = t.test(x, y)$p.value)
}))
res$p_holm <- p.adjust(res$p, method = "holm")
res
```
## Python(seaborn / matplotlib)
```{pyodide}
pairs = [("アデリー", "ヒゲ"), ("ヒゲ", "ジェンツー"), ("アデリー", "ジェンツー")] # 短い線を先(下)に、長い線を後(上)に
rows = []
for g1, g2 in pairs:
x = peng.loc[peng["種"] == g1, "body_mass_g"]; y = peng.loc[peng["種"] == g2, "body_mass_g"]
rows.append({"群1": g1, "群2": g2, "差": y.mean() - x.mean(),
"p": stats.ttest_ind(x, y, equal_var=False).pvalue})
res = pd.DataFrame(rows)
res["p_holm"] = multipletests(res["p"], method="holm")[1]
res
```
:::
アデリーとヒゲの差は 27 g で p = 0.65(補正後も 0.65)、ジェンツーとほかの 2 種の差は約 1360〜1390 g で、p は非常に小さくなりました。
## 3. p 値を記号にする
よく使われる対応は次のとおりですが、**雑誌や分野によって違う** ので、図の説明に必ず書きます。
| p 値 | 記号 |
|---|---|
| p ≥ 0.05 | ns(有意差なし) |
| p < 0.05 | \* |
| p < 0.01 | \*\* |
| p < 0.001 | \*\*\* |
| p < 0.0001 | \*\*\*\* |
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
p_to_star <- function(p) {
cut(p, breaks = c(-Inf, 1e-4, 1e-3, 0.01, 0.05, Inf),
labels = c("****", "***", "**", "*", "ns"), right = FALSE) |> as.character()
}
res$記号 <- p_to_star(res$p_holm)
res
```
## Python(seaborn / matplotlib)
```{pyodide}
def p_to_star(p):
for thr, s in [(1e-4, "****"), (1e-3, "***"), (0.01, "**"), (0.05, "*")]:
if p < thr:
return s
return "ns"
res["記号"] = res["p_holm"].map(p_to_star)
res
```
:::
## 4. 線と記号を描く
### カテゴリの軸の「位置」を知る
線を引くには、各群の **横軸の位置(数値)** が必要です。
- ggplot2:カテゴリの軸の位置は、**1, 2, 3, …**(因子の水準の順)
- seaborn:カテゴリの軸の位置は、**0, 1, 2, …**
高さは、比べる 2 群のデータの最大値より少し上にし、線が重ならないように **1 本ずつ上にずらします**。
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
ymax <- max(peng$body_mass_g)
step <- 0.08 * diff(range(peng$body_mass_g)) # 線の間隔(データの範囲の 8%)
brk <- res |>
mutate(x1 = as.integer(factor(群1, levels(peng$種))), # 群の位置(1, 2, 3)
x2 = as.integer(factor(群2, levels(peng$種))),
y = ymax + step * seq_len(n())) # 1 本ずつ上に
brk
ggplot(peng, aes(種, body_mass_g)) +
geom_boxplot(outlier.shape = NA, width = 0.5) +
geom_point(position = position_jitter(width = 0.12, height = 0, seed = 1), alpha = 0.4, size = 1) +
geom_segment(data = brk, aes(x = x1, xend = x2, y = y, yend = y), inherit.aes = FALSE) + # 横線
geom_segment(data = brk, aes(x = x1, xend = x1, y = y, yend = y - step * 0.25), inherit.aes = FALSE) + # 左の縦線
geom_segment(data = brk, aes(x = x2, xend = x2, y = y, yend = y - step * 0.25), inherit.aes = FALSE) + # 右の縦線
geom_text(data = brk, aes(x = (x1 + x2) / 2, y = y, label = 記号),
vjust = ifelse(brk$記号 == "ns", -0.4, 0.2), size = 4.5, inherit.aes = FALSE) +
labs(x = NULL, y = "体重 (g)")
```
## Python(seaborn / matplotlib)
```{pyodide}
levels = list(peng["種"].cat.categories)
ymax = peng["body_mass_g"].max()
step = 0.08 * (peng["body_mass_g"].max() - peng["body_mass_g"].min())
def bracket(ax, x1, x2, y, text, h, fontsize=13):
"""x1 と x2 の間に、高さ y の線(両端を h だけ下に曲げる)と文字を描く"""
ax.plot([x1, x1, x2, x2], [y - h, y, y, y - h], color="black", lw=1)
ax.text((x1 + x2) / 2, y, text, ha="center", va="bottom", fontsize=fontsize if text != "ns" else 10)
fig, ax = plt.subplots()
sns.boxplot(data=peng, x="種", y="body_mass_g", showfliers=False, width=0.5, fill=False, color="black", ax=ax)
np.random.seed(1)
sns.stripplot(data=peng, x="種", y="body_mass_g", jitter=0.12, alpha=0.4, size=3, ax=ax)
for i, r in res.iterrows():
x1, x2 = levels.index(r["群1"]), levels.index(r["群2"]) # 群の位置(0, 1, 2)
bracket(ax, x1, x2, ymax + step * (i + 1), r["記号"], h=step * 0.25)
ax.set(xlabel="", ylabel="体重 (g)")
ax.set_ylim(top=ymax + step * (len(res) + 1.5)) # 上に余白を作る
plt.show()
```
:::
::: {.callout-tip}
## 線を重ねる順番
長い線(アデリー〜ジェンツー)を下に置くと、その上の記号が短い線とぶつかります。**短い線を下、長い線を上** に積むのが基本です。記号と上の線が近すぎるときは、線の間隔(`step`)を広げます。
:::
::: {.callout-tip}
## 位置を「データの値」で決めると、どの図にも使える
線の高さをデータの最大値と範囲から計算しているので、変数を変えても(ひれの長さ、くちばしの深さ)同じコードで描けます。
`ymax` と `step` を群ごとの最大値から計算すれば、線を短くまとめることもできます。
:::
### 関数にまとめる
何度も使うので、「データ・群の列・値の列・比較の表」から図を作る関数にしておきます。
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
add_brackets <- function(p, res, levels, yvals, step_frac = 0.08, tip = 0.25, size = 4.5) {
ymax <- max(yvals, na.rm = TRUE); step <- step_frac * diff(range(yvals, na.rm = TRUE))
b <- res |> mutate(x1 = match(群1, levels), x2 = match(群2, levels), y = ymax + step * seq_len(n()))
p +
geom_segment(data = b, aes(x = x1, xend = x2, y = y, yend = y), inherit.aes = FALSE) +
geom_segment(data = b, aes(x = x1, xend = x1, y = y, yend = y - step * tip), inherit.aes = FALSE) +
geom_segment(data = b, aes(x = x2, xend = x2, y = y, yend = y - step * tip), inherit.aes = FALSE) +
geom_text(data = b, aes(x = (x1 + x2) / 2, y = y, label = 記号), vjust = -0.1, size = size, inherit.aes = FALSE)
}
pairwise_res <- function(d, group, value, pairs) {
r <- do.call(rbind, lapply(pairs, function(pr) {
data.frame(群1 = pr[1], 群2 = pr[2],
p = t.test(d[[value]][d[[group]] == pr[1]], d[[value]][d[[group]] == pr[2]])$p.value)
}))
r$p_holm <- p.adjust(r$p, "holm"); r$記号 <- p_to_star(r$p_holm); r
}
r_fl <- pairwise_res(peng, "種", "flipper_length_mm", pairs)
p <- ggplot(peng, aes(種, flipper_length_mm, fill = 種)) +
geom_violin(alpha = 0.4, colour = NA) + geom_boxplot(width = 0.15, outlier.shape = NA, fill = "white") +
theme(legend.position = "none") + labs(x = NULL, y = "ひれの長さ (mm)")
add_brackets(p, r_fl, levels(peng$種), peng$flipper_length_mm)
```
## Python(seaborn / matplotlib)
```{pyodide}
def pairwise_res(d, group, value, pairs):
rows = [{"群1": a, "群2": b,
"p": stats.ttest_ind(d.loc[d[group] == a, value], d.loc[d[group] == b, value], equal_var=False).pvalue}
for a, b in pairs]
r = pd.DataFrame(rows); r["p_holm"] = multipletests(r["p"], method="holm")[1]
r["記号"] = r["p_holm"].map(p_to_star); return r
def add_brackets(ax, res, levels, yvals, step_frac=0.08, tip=0.25):
ymax = np.nanmax(yvals); step = step_frac * (np.nanmax(yvals) - np.nanmin(yvals))
for i, r in enumerate(res.itertuples()):
bracket(ax, levels.index(r.群1), levels.index(r.群2), ymax + step * (i + 1), r.記号, h=step * tip)
ax.set_ylim(top=ymax + step * (len(res) + 1.5))
r_fl = pairwise_res(peng, "種", "flipper_length_mm", pairs)
fig, ax = plt.subplots()
sns.violinplot(data=peng, x="種", y="flipper_length_mm", hue="種", alpha=0.4, inner=None, linewidth=0, legend=False, ax=ax)
sns.boxplot(data=peng, x="種", y="flipper_length_mm", width=0.15, showfliers=False, color="white", ax=ax)
add_brackets(ax, r_fl, levels, peng["flipper_length_mm"])
ax.set(xlabel="", ylabel="ひれの長さ (mm)")
plt.show()
```
:::
## 群の中を 2 つに分けたとき(dodge)
種ごとに **オスとメス** を比べる図では、箱が横にずれて並ぶので、線の位置も **ずらした位置** にする必要があります。
- ggplot2:`position_dodge(width = 0.75)` で 2 群なら、中心から **± 0.75 / 4 = ± 0.1875**
- seaborn:`hue` で 2 群なら(既定の幅 0.8)、中心から **± 0.2**
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
sex_res <- peng |> group_by(種) |>
summarise(p = t.test(body_mass_g ~ 性別)$p.value, y = max(body_mass_g)) |>
mutate(記号 = p_to_star(p), x = as.integer(種)) # 種ごとに 1 回ずつの比較(3 回)
sex_res
off <- 0.75 / 4; h <- 60
ggplot(peng, aes(種, body_mass_g, fill = 性別)) +
geom_boxplot(outlier.shape = NA, position = position_dodge(0.75), width = 0.6) +
geom_point(position = position_jitterdodge(jitter.width = 0.15, dodge.width = 0.75, seed = 1),
alpha = 0.4, size = 0.8) +
geom_segment(data = sex_res, aes(x = x - off, xend = x + off, y = y + 2 * h, yend = y + 2 * h), inherit.aes = FALSE) +
geom_segment(data = sex_res, aes(x = x - off, xend = x - off, y = y + 2 * h, yend = y + h), inherit.aes = FALSE) +
geom_segment(data = sex_res, aes(x = x + off, xend = x + off, y = y + 2 * h, yend = y + h), inherit.aes = FALSE) +
geom_text(data = sex_res, aes(x = x, y = y + 2 * h, label = 記号), vjust = -0.1, size = 4.5, inherit.aes = FALSE) +
labs(x = NULL, y = "体重 (g)", fill = "性別")
```
## Python(seaborn / matplotlib)
```{pyodide}
fig, ax = plt.subplots()
sns.boxplot(data=peng, x="種", y="body_mass_g", hue="性別", showfliers=False, width=0.8, ax=ax)
np.random.seed(1)
sns.stripplot(data=peng, x="種", y="body_mass_g", hue="性別", dodge=True, jitter=0.1,
size=2.5, alpha=0.5, palette=["0.3", "0.3"], legend=False, ax=ax)
off, h = 0.2, 60
for i, sp in enumerate(levels):
d = peng[peng["種"] == sp]
p = stats.ttest_ind(d.loc[d["性別"] == "メス", "body_mass_g"], d.loc[d["性別"] == "オス", "body_mass_g"],
equal_var=False).pvalue
bracket(ax, i - off, i + off, d["body_mass_g"].max() + 2 * h, p_to_star(p), h=h)
ax.set(xlabel="", ylabel="体重 (g)")
ax.set_ylim(top=peng["body_mass_g"].max() + 6 * h)
ax.legend(title="性別", loc="upper left")
plt.show()
```
:::
::: {.callout-note}
## この 3 回の比較に補正は必要か
「各種の中でオスとメスを比べる」3 回の検定は、それぞれ別の問いと考えて補正しないこともあれば、まとめて補正することもあります。どちらにしたかを、図の説明に書きます。
:::
## パッケージを使う:ggsignif
R の `ggsignif` は、`geom_signif()` で線とアスタリスクを描いてくれます。
```{webr}
library(ggsignif)
ggplot(peng, aes(種, body_mass_g)) +
geom_boxplot(outlier.shape = NA, width = 0.5) +
geom_signif(comparisons = pairs, test = "t.test", map_signif_level = TRUE, step_increase = 0.08) +
labs(x = NULL, y = "体重 (g)", title = "ggsignif に検定もまかせた場合(補正なし)")
```
::: {.callout-warning}
## パッケージに検定をまかせると、補正されない
`geom_signif(test = ...)` は、**比較ごとに独立に検定し、多重比較の補正をしません**。また、t 検定の種類(Welch かどうか)も既定値任せになります。
検定は自分で行い、結果だけを `annotations =`(記号)・`y_position =`(高さ)・`xmin =`, `xmax =`(位置)で渡すのが安全です。
:::
```{webr}
ggplot(peng, aes(種, body_mass_g)) +
geom_boxplot(outlier.shape = NA, width = 0.5) +
geom_signif(xmin = match(res$群1, levels(peng$種)), xmax = match(res$群2, levels(peng$種)),
y_position = max(peng$body_mass_g) + c(150, 400, 650),
annotations = res$記号, tip_length = 0.02, textsize = 4.5) +
labs(x = NULL, y = "体重 (g)", title = "自分で検定・補正した結果を渡した場合")
```
Python では、`statannotations` というパッケージが同じ役割を持ちますが、seaborn 0.13 との組み合わせで動かないことが多いため、このハンズオンでは上の `bracket()` のように自分で描く方法を勧めます。
## アスタリスクの前に考えること
::: {.callout-warning}
## アスタリスクは、情報を大きく減らす
- アスタリスクは「p 値がどの閾値より小さいか」しか伝えない。**差の大きさ・向き・信頼区間** は分からない
- 「ns」は「差がない」ではない(χ² 検定ハンズオン第 8 章)
- たくさんの組み合わせに線を引くと、図が読めなくなり、多重比較の問題も大きくなる。**比べる組み合わせを事前に決める**
- 図の説明に、**検定の名前・補正の方法・記号の対応・各群の人数** を書く
- 可能なら、アスタリスクの代わりに **p 値そのもの**(p = 0.003)や、**差と 95% 信頼区間** を示す
:::
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
# アスタリスクの代わりに p 値を書く例
brk$ラベル <- ifelse(brk$p_holm < 0.001, "p < 0.001", sprintf("p = %.2f", brk$p_holm))
ggplot(peng, aes(種, body_mass_g)) +
geom_boxplot(outlier.shape = NA, width = 0.5) +
geom_point(position = position_jitter(width = 0.12, height = 0, seed = 1), alpha = 0.4, size = 1) +
geom_segment(data = brk, aes(x = x1, xend = x2, y = y, yend = y), inherit.aes = FALSE) +
geom_text(data = brk, aes(x = (x1 + x2) / 2, y = y, label = ラベル), vjust = -0.4, size = 3.5, inherit.aes = FALSE) +
labs(x = NULL, y = "体重 (g)", caption = "Welch の t 検定、Holm の方法で補正")
```
## Python(seaborn / matplotlib)
```{pyodide}
fig, ax = plt.subplots()
sns.boxplot(data=peng, x="種", y="body_mass_g", showfliers=False, width=0.5, fill=False, color="black", ax=ax)
for i, r in res.iterrows():
lab = "p < 0.001" if r["p_holm"] < 0.001 else f"p = {r['p_holm']:.2f}"
bracket(ax, levels.index(r["群1"]), levels.index(r["群2"]), ymax + step * (i + 1), lab, h=step * 0.25, fontsize=10)
ax.set_ylim(top=ymax + step * 4.5)
ax.set(xlabel="", ylabel="体重 (g)")
fig.text(0.99, 0.01, "Welch の t 検定、Holm の方法で補正", ha="right", fontsize=9, color="0.4")
plt.show()
```
:::
::: {.callout-important}
## この章のまとめ
- **検定と補正は自分で** 行い、結果の表から線と記号を描く
- カテゴリの位置は ggplot2 で **1, 2, 3**、seaborn で **0, 1, 2**。dodge したときは中心から ±(幅 / 4) や ±0.2
- 線の高さは **データの最大値と範囲** から計算し、1 本ずつ上にずらす。上に余白を作る
- `ggsignif` に検定をまかせると **補正されない**。記号と位置を渡す
- アスタリスクより、**p 値・差と信頼区間** のほうが情報が多い。検定・補正・記号の意味を必ず書く
:::