---
webr:
packages: [dplyr, ggplot2, ggbeeswarm, 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: true
pyodide:
packages: [pandas, matplotlib, seaborn]
cell-options:
autorun: true
---
{{< include ./_extensions/r-wasm/live/_knitr.qmd >}}
# 分布:ヒストグラム・箱ひげ図・点・誤差棒 {#sec-distribution}
```{webr}
#| include: false
source("R/setup.R")
library(patchwork)
library(ggbeeswarm)
peng <- penguins |> filter(!is.na(sex)) |>
mutate(種 = factor(species, c("Adelie", "Chinstrap", "Gentoo"), c("アデリー", "ヒゲ", "ジェンツー")))
```
```{pyodide}
#| include: false
exec(open("py/setup.py").read())
peng = penguins.dropna(subset=["sex"]).copy()
peng["種"] = pd.Categorical(peng["species"].map({"Adelie": "アデリー", "Chinstrap": "ヒゲ", "Gentoo": "ジェンツー"}),
categories=["アデリー", "ヒゲ", "ジェンツー"])
```
群ごとの値の分布を比べる図は、臨床研究の図でもっとも多い形です。描き方によって、**見えるもの・隠れるもの** が大きく変わります。
## ヒストグラム:ビンの幅で形が変わる
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
h <- function(w) ggplot(peng, aes(flipper_length_mm)) +
geom_histogram(binwidth = w, fill = "grey60", colour = "white") +
labs(x = "ひれの長さ (mm)", y = "羽数", title = paste0("ビンの幅 ", w, " mm"))
h(2) + h(5) + h(15)
```
## Python(seaborn / matplotlib)
```{pyodide}
fig, axes = plt.subplots(1, 3, figsize=(12, 3.5))
for ax, w in zip(axes, [2, 5, 15]):
sns.histplot(data=peng, x="flipper_length_mm", binwidth=w, color="grey", ax=ax)
ax.set(xlabel="ひれの長さ (mm)", ylabel="羽数", title=f"ビンの幅 {w} mm")
plt.tight_layout()
plt.show()
```
:::
ビンの幅が 5 mm だと **2 つの山**(アデリー・ヒゲと、ジェンツー)が見えますが、15 mm では 1 つの山に見えます。
ヒストグラムは、ビンの幅を何通りか変えて確かめます。
## 箱ひげ図は何を表しているか
箱ひげ図の各部分は、次の値です。
- **箱の中の線**:中央値
- **箱の上下**:第 1 四分位点(25%)と第 3 四分位点(75%)。箱の高さが四分位範囲(IQR)
- **ひげ**:箱の端から **1.5 × IQR 以内にある、いちばん端のデータ** まで
- **点**:ひげの外のデータ(外れ値の候補)
手で計算して、図と照らし合わせます。
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
x <- peng$body_mass_g[peng$種 == "ジェンツー"]
q <- quantile(x, c(0.25, 0.5, 0.75)); iqr <- q[3] - q[1]
c(q, 下のひげ = min(x[x >= q[1] - 1.5 * iqr]), 上のひげ = max(x[x <= q[3] + 1.5 * iqr]))
ggplot(peng, aes(種, body_mass_g)) + geom_boxplot() + labs(x = NULL, y = "体重 (g)")
```
## Python(seaborn / matplotlib)
```{pyodide}
x = peng.loc[peng["種"] == "ジェンツー", "body_mass_g"]
q1, q2, q3 = x.quantile([0.25, 0.5, 0.75]); iqr = q3 - q1
print(q1, q2, q3, "ひげ:", x[x >= q1 - 1.5 * iqr].min(), x[x <= q3 + 1.5 * iqr].max())
fig, ax = plt.subplots()
sns.boxplot(data=peng, x="種", y="body_mass_g", ax=ax)
ax.set(xlabel="", ylabel="体重 (g)")
plt.show()
```
:::
::: {.callout-note}
## 四分位点の計算方法
四分位点の計算方法には何種類もあります。R の `quantile()` の既定(type 7)と、pandas・NumPy の既定(線形補間)は同じ方法なので、両者の箱ひげ図は一致します。SPSS や Excel の一部の関数は別の方法を使うことがあり、少数のデータでは値がずれます。
:::
## 箱ひげ図が隠すもの
**山が 2 つある分布** と **山が 1 つの分布** を、同じような四分位点になるように作ってみます。
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
set.seed(1)
demo <- data.frame(
群 = rep(c("山が 1 つ", "山が 2 つ"), each = 200),
値 = c(rnorm(200, 50, 15), c(rnorm(100, 35, 4), rnorm(100, 65, 4))))
p_box <- ggplot(demo, aes(群, 値)) + geom_boxplot() + labs(title = "箱ひげ図", x = NULL)
p_vio <- ggplot(demo, aes(群, 値)) + geom_violin(fill = "grey85") + labs(title = "バイオリン", x = NULL)
p_pts <- ggplot(demo, aes(群, 値)) + geom_quasirandom(size = 0.8, alpha = 0.6) + labs(title = "点(蜂群)", x = NULL)
p_box + p_vio + p_pts
```
## Python(seaborn / matplotlib)
```{pyodide}
rng = np.random.default_rng(1)
demo = pd.DataFrame({
"群": ["山が 1 つ"] * 200 + ["山が 2 つ"] * 200,
"値": np.r_[rng.normal(50, 15, 200), rng.normal(35, 4, 100), rng.normal(65, 4, 100)]})
fig, axes = plt.subplots(1, 3, figsize=(12, 3.8), sharey=True)
sns.boxplot(data=demo, x="群", y="値", ax=axes[0]); axes[0].set_title("箱ひげ図")
sns.violinplot(data=demo, x="群", y="値", color="0.85", ax=axes[1]); axes[1].set_title("バイオリン")
sns.swarmplot(data=demo, x="群", y="値", size=2.5, ax=axes[2]); axes[2].set_title("点(蜂群)")
for a in axes: a.set_xlabel("")
plt.tight_layout()
plt.show()
```
:::
箱ひげ図では 2 つの群はよく似ていますが、バイオリン図や点を見ると、右の群には **真ん中の値がほとんどない** ことが分かります。
人数が数十人くらいまでなら、**点をすべて見せる** のがいちばん正直です。
## 箱ひげ図に点を重ねる
よく使われるのが、箱ひげ図に点を重ねる形です。このとき、**箱ひげ図の外れ値の点を消す** のを忘れると、外れ値が 2 回描かれます。
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
ggplot(peng, aes(種, body_mass_g, colour = 種)) +
geom_boxplot(outlier.shape = NA, width = 0.5) + # 外れ値の点を描かない
geom_point(alpha = 0.5, size = 1.2,
position = position_jitter(width = 0.15, height = 0, seed = 1)) + # 横にずらす。seed で毎回同じずらし方に
theme(legend.position = "none") +
labs(x = NULL, y = "体重 (g)")
```
## Python(seaborn / matplotlib)
```{pyodide}
fig, ax = plt.subplots()
sns.boxplot(data=peng, x="種", y="body_mass_g", hue="種", showfliers=False, width=0.5,
fill=False, legend=False, ax=ax) # 外れ値を描かない・箱を塗らない
sns.stripplot(data=peng, x="種", y="body_mass_g", hue="種", jitter=0.15, alpha=0.5, size=4,
legend=False, ax=ax)
ax.set(xlabel="", ylabel="体重 (g)")
plt.show()
```
:::
::: {.callout-tip}
## ずらし(jitter)は乱数
点を横にずらす量は乱数で決まるので、実行するたびに図が少し変わります。論文の図は、R なら `position_jitter(seed = )`、seaborn なら実行前に `np.random.seed()` を指定して再現できるようにします。
:::
### 2 つのカテゴリで分ける
性別でも分けると、箱と点の **横の位置をそろえる** 必要があります(`dodge`)。
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
ggplot(peng, aes(種, body_mass_g, fill = sex)) +
geom_boxplot(outlier.shape = NA, width = 0.6, position = position_dodge(width = 0.75), alpha = 0.5) +
geom_point(aes(colour = sex), size = 1, alpha = 0.6,
position = position_jitterdodge(jitter.width = 0.15, dodge.width = 0.75, seed = 1)) +
labs(x = NULL, y = "体重 (g)", fill = "性別", colour = "性別")
```
## Python(seaborn / matplotlib)
```{pyodide}
fig, ax = plt.subplots()
sns.boxplot(data=peng, x="種", y="body_mass_g", hue="sex", showfliers=False, width=0.6,
boxprops={"alpha": 0.5}, ax=ax)
sns.stripplot(data=peng, x="種", y="body_mass_g", hue="sex", dodge=True, jitter=0.12,
size=3, alpha=0.6, legend=False, ax=ax)
ax.set(xlabel="", ylabel="体重 (g)")
ax.legend(title="性別")
plt.show()
```
:::
## 平均と誤差棒:SD・SE・95% 信頼区間
平均を点で示し、**誤差棒** をつける図もよく使われます。誤差棒が何を表すかで、意味がまったく違います。
| 誤差棒 | 表すもの | 人数が増えると |
|---|---|---|
| **SD**(標準偏差) | 1 羽ごとの値のばらつき | 変わらない |
| **SE**(標準誤差 = SD / √n) | 平均の推定の不確かさ | 小さくなる |
| **95% 信頼区間**(≒ 平均 ± 1.96 SE) | 平均がありそうな範囲 | 小さくなる |
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
summ <- peng |> group_by(種) |>
summarise(n = n(), 平均 = mean(body_mass_g), SD = sd(body_mass_g), SE = SD / sqrt(n),
CI = qt(0.975, n - 1) * SE)
summ
eb <- function(w, lab) ggplot(summ, aes(種, 平均)) +
geom_point(size = 2.5) +
geom_errorbar(aes(ymin = 平均 - .data[[w]], ymax = 平均 + .data[[w]]), width = 0.15) +
coord_cartesian(ylim = c(3000, 6000)) + labs(x = NULL, y = "体重 (g)", title = lab)
eb("SD", "平均 ± SD") + eb("SE", "平均 ± SE") + eb("CI", "平均と 95% CI")
```
## Python(seaborn / matplotlib)
```{pyodide}
fig, axes = plt.subplots(1, 3, figsize=(12, 3.8), sharey=True)
for ax, (eb, lab) in zip(axes, [("sd", "平均 ± SD"), ("se", "平均 ± SE"), (("ci", 95), "平均と 95% CI")]):
sns.pointplot(data=peng, x="種", y="body_mass_g", errorbar=eb, linestyle="none",
capsize=0.15, seed=1, ax=ax)
ax.set(xlabel="", ylabel="体重 (g)", title=lab, ylim=(3000, 6000))
plt.tight_layout()
plt.show()
```
:::
同じデータでも、SE や CI の誤差棒は SD よりずっと短く、**群の差が大きく見えます**。
図の説明(凡例・キャプション)に、**誤差棒が何かを必ず書きます**。
::: {.callout-warning}
## seaborn の既定の誤差棒は「ブートストラップの 95% CI」
seaborn の `pointplot()`・`barplot()`・`lineplot()` は、何も指定しないと **ブートストラップ(乱数)で計算した 95% 信頼区間** を描きます。実行するたびに少し変わり、t 分布による CI とも少し違います。
`errorbar=("ci", 95)` と明示し、`seed=` を指定するか、`errorbar="se"` や `errorbar="sd"` を使い、何を描いたかを書きます。
:::
::: {.callout-warning}
## 棒グラフ+誤差棒(ダイナマイトプロット)を避ける
平均を棒の高さで示し、上に誤差棒をつける図は、**分布の形・人数・外れ値がすべて隠れる** ため、多くの雑誌で避けるよう勧められています。点や箱ひげ図+点を使います。
:::
::: {.callout-important}
## この章のまとめ
- ヒストグラムは **ビンの幅** を何通りか試す
- 箱ひげ図は **中央値・四分位・1.5 × IQR のひげ・外れ値**。**山が 2 つある分布を隠す**
- 点を重ねるときは、**箱の外れ値を消し**、ずらしの **乱数の種** を固定する
- 誤差棒は **SD・SE・CI のどれかを必ず明記**。seaborn の既定はブートストラップの CI
:::