---
webr:
packages: [dplyr, ggplot2]
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-regression}
```{webr}
#| include: false
source("R/setup.R")
pb <- penguins |> filter(!is.na(bill_length_mm), !is.na(bill_depth_mm))
sp_cols <- c(Adelie = "#E69F00", Chinstrap = "#56B4E9", Gentoo = "#009E73")
```
```{pyodide}
#| include: false
exec(open("py/setup.py").read())
from scipy import stats
import statsmodels.formula.api as smf
pb = penguins.dropna(subset=["bill_length_mm", "bill_depth_mm"]).copy()
sp_cols = {"Adelie": "#E69F00", "Chinstrap": "#56B4E9", "Gentoo": "#009E73"}
```
散布図に **回帰直線** を引き、**式(y = ax + b)・決定係数 R²・p 値** を書き込む図を作ります。
くちばしの **長さ** と **深さ** の関係を使います。
## 回帰直線と信頼帯
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
ggplot(pb, aes(bill_length_mm, bill_depth_mm)) +
geom_point(alpha = 0.5) +
geom_smooth(method = "lm", formula = y ~ x) + # 直線(最小二乗法)と 95% 信頼帯
labs(x = "くちばしの長さ (mm)", y = "くちばしの深さ (mm)")
```
`geom_smooth()` は、何も指定しないと **局所回帰(loess)などの曲線** を描きます。直線にしたいときは、必ず `method = "lm"` を指定します。
## Python(seaborn / matplotlib)
```{pyodide}
fig, ax = plt.subplots()
sns.regplot(data=pb, x="bill_length_mm", y="bill_depth_mm", scatter_kws={"alpha": 0.5, "s": 15},
line_kws={"color": "C1"}, seed=1, ax=ax)
ax.set(xlabel="くちばしの長さ (mm)", ylabel="くちばしの深さ (mm)")
plt.show()
```
seaborn の `regplot()` の帯は、既定で **ブートストラップ(乱数)で計算した 95% 信頼区間** です。`seed=` で再現できるようにします。
:::
くちばしが長いほど、浅い(右下がり)ように見えます。この直線の式を求めて、図に書き込みます。
## 式・R²・p 値を計算する
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
fit <- lm(bill_depth_mm ~ bill_length_mm, data = pb)
s <- summary(fit)
b0 <- coef(fit)[1]; b1 <- coef(fit)[2]
c(切片 = b0, 傾き = b1, R2 = s$r.squared, p = coef(s)[2, 4])
```
## Python(seaborn / matplotlib)
```{pyodide}
r = stats.linregress(pb["bill_length_mm"], pb["bill_depth_mm"])
print(f"切片 {r.intercept:.4f} 傾き {r.slope:.5f} R2 {r.rvalue**2:.4f} p {r.pvalue:.2e}")
```
`scipy.stats.linregress()` は、1 変数の直線回帰の傾き・切片・相関係数・p 値を返します。複数の変数を使うなら `statsmodels` を使います(後述)。
:::
**y = −0.085x + 20.89、R² = 0.055、p = 1.1 × 10⁻⁵** です。
### 式を文字列にする:符号に注意
切片が負のとき、そのまま `paste` すると「y = 0.2x + -5.3」になってしまいます。符号を見て「+」「−」を切り替える関数を作っておきます。ついでに、ハイフン(-)を数学のマイナス記号(−、U+2212)に置き換えます。
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
eq_label <- function(fit, digits = 3) {
b <- coef(fit); r2 <- summary(fit)$r.squared
sgn <- ifelse(b[1] < 0, "−", "+") # U+2212(数学のマイナス記号)
lab <- sprintf("y = %.*fx %s %.*f\nR² = %.3f", digits, b[2], sgn, digits, abs(b[1]), r2)
sub("-", "\u2212", lab, fixed = TRUE) # 傾きが負のときも数学のマイナス記号に
}
cat(eq_label(fit))
```
## Python(seaborn / matplotlib)
```{pyodide}
def eq_label(slope, intercept, r2, digits=3):
sgn = "−" if intercept < 0 else "+"
lab = f"y = {slope:.{digits}f}x {sgn} {abs(intercept):.{digits}f}\nR² = {r2:.3f}"
return lab.replace("-", "\u2212", 1) # 傾きが負のときも数学のマイナス記号に
print(eq_label(r.slope, r.intercept, r.rvalue**2))
```
:::
## 式を図に書き込む:「データの座標」と「パネルの座標」
テキストの位置の指定には、2 つの考え方があります。
- **データの座標**:x = 55 mm、y = 21 mm のように、軸の値で指定する。データが変わると、はみ出したり点と重なったりする
- **パネルの座標**:「パネルの左上から 5% の位置」のように、図の枠に対する割合で指定する。どんなデータでも同じ場所に置ける
式のような注記は、**パネルの座標** で置くのが便利です。
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
ggplot(pb, aes(bill_length_mm, bill_depth_mm)) +
geom_point(alpha = 0.5) +
geom_smooth(method = "lm", formula = y ~ x) +
annotate("text", x = -Inf, y = Inf, label = eq_label(fit), # -Inf, Inf = 左上の角
hjust = -0.1, vjust = 1.2, size = 4.2) + # 角から少し内側にずらす
labs(x = "くちばしの長さ (mm)", y = "くちばしの深さ (mm)")
```
ggplot2 では、位置に **`-Inf` / `Inf`** を指定すると、パネルの端になります。`hjust`・`vjust`(文字の基準点。0 が左・下、1 が右・上)で内側に寄せます。
## Python(seaborn / matplotlib)
```{pyodide}
fig, ax = plt.subplots()
sns.regplot(data=pb, x="bill_length_mm", y="bill_depth_mm", scatter_kws={"alpha": 0.5, "s": 15}, seed=1, ax=ax)
ax.text(0.03, 0.97, eq_label(r.slope, r.intercept, r.rvalue**2),
transform=ax.transAxes, # (0, 0) が左下、(1, 1) が右上の「パネルの座標」
ha="left", va="top", fontsize=11,
bbox=dict(boxstyle="round", fc="white", ec="0.7"))
ax.set(xlabel="くちばしの長さ (mm)", ylabel="くちばしの深さ (mm)")
plt.show()
```
matplotlib では、`transform=ax.transAxes` を指定すると、位置が **パネルの座標**(0〜1)になります。`ha`・`va` は文字の基準点です。座標変換は第 9 章で詳しく扱います。
:::
## 数式の書式:上付き・斜体
R² の「2」を上付きにしたり、変数を斜体にしたりするには、数式の書式を使います。
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
r2 <- summary(fit)$r.squared; pval <- coef(summary(fit))[2, 4]
ex <- floor(log10(pval)); man <- pval / 10^ex # p 値を「仮数 × 10 の指数」に分ける
lab <- sprintf("italic(R)^2 == %.3f*\",\"~~italic(p) == %.1f %%*%% 10^%d", # plotmath の書き方
r2, man, ex)
lab
ggplot(pb, aes(bill_length_mm, bill_depth_mm)) +
geom_point(alpha = 0.5) +
geom_smooth(method = "lm", formula = y ~ x) +
annotate("text", x = -Inf, y = Inf, label = lab, parse = TRUE, hjust = -0.1, vjust = 1.5, size = 4.2) +
labs(x = "くちばしの長さ (mm)", y = "くちばしの深さ (mm)")
```
`parse = TRUE` にすると、ラベルが R の **plotmath**(数式の書き方)として解釈されます。`^` で上付き、`italic()` で斜体、`==` で等号、`%*%` で ×、`~` で空白、`*` で連結です。
## Python(seaborn / matplotlib)
```{pyodide}
fig, ax = plt.subplots()
sns.regplot(data=pb, x="bill_length_mm", y="bill_depth_mm", scatter_kws={"alpha": 0.5, "s": 15}, seed=1, ax=ax)
ex = int(np.floor(np.log10(r.pvalue))) # p 値を「仮数 × 10 の指数」に分ける
man = r.pvalue / 10**ex
ax.text(0.03, 0.97, rf"$R^2 = {r.rvalue**2:.3f}$, $p = {man:.1f} \times 10^{{{ex}}}$",
transform=ax.transAxes, ha="left", va="top", fontsize=12)
ax.set(xlabel="くちばしの長さ (mm)", ylabel="くちばしの深さ (mm)")
plt.show()
```
matplotlib では、`$...$` で囲むと **mathtext**(LaTeX に似た数式の書き方)になります。`^` で上付き、`\times` で ×、`{}` で範囲を指定します。
`$...$` の中では日本語が使えないので、日本語は `$` の外に書きます。
:::
## 群ごとに直線と式を描く
ここで、種ごとに色を分けてみます。
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
eqs <- pb |> group_by(species) |>
group_modify(~ {
f <- lm(bill_depth_mm ~ bill_length_mm, data = .x)
tibble(傾き = coef(f)[2], 切片 = coef(f)[1], R2 = summary(f)$r.squared,
label = sprintf("%s: y = %.2fx + %.2f, R² = %.2f", .y$species, coef(f)[2], coef(f)[1], summary(f)$r.squared))
}) |> ungroup() |>
mutate(行 = row_number())
eqs
ggplot(pb, aes(bill_length_mm, bill_depth_mm, colour = species)) +
geom_point(alpha = 0.5) +
geom_smooth(method = "lm", formula = y ~ x, se = FALSE) +
geom_smooth(aes(group = 1), method = "lm", formula = y ~ x, se = FALSE, colour = "black", linetype = 2) + # 全体の直線
geom_text(data = eqs, aes(x = -Inf, y = Inf, label = label, vjust = 1.3 + 1.5 * (行 - 1)),
hjust = -0.05, size = 3.6, show.legend = FALSE) +
scale_colour_manual(values = sp_cols) +
scale_y_continuous(expand = expansion(mult = c(0.05, 0.35))) + # 上に 35% の余白を作り、式を置く
labs(x = "くちばしの長さ (mm)", y = "くちばしの深さ (mm)", colour = "種", caption = "黒の破線:3 種をまとめた回帰直線")
```
式を **1 行ずつずらす** ために、`vjust` を行番号で増やしています(`vjust` は文字の高さを単位にしたずれ)。式が点と重ならないように、`expansion()` で縦軸の上に余白を作っています。
## Python(seaborn / matplotlib)
```{pyodide}
fig, ax = plt.subplots(figsize=(7.5, 4.5))
for i, (sp, d) in enumerate(pb.groupby("species")):
rr = stats.linregress(d["bill_length_mm"], d["bill_depth_mm"])
sns.regplot(data=d, x="bill_length_mm", y="bill_depth_mm", ci=None, color=sp_cols[sp],
scatter_kws={"alpha": 0.5, "s": 15}, label=sp, ax=ax)
ax.text(0.02, 0.97 - 0.07 * i, f"{sp}: y = {rr.slope:.2f}x + {rr.intercept:.2f}, R² = {rr.rvalue**2:.2f}",
transform=ax.transAxes, color=sp_cols[sp], ha="left", va="top", fontsize=10)
sns.regplot(data=pb, x="bill_length_mm", y="bill_depth_mm", ci=None, scatter=False,
line_kws={"color": "black", "ls": "--"}, ax=ax)
lo, hi = pb["bill_depth_mm"].min(), pb["bill_depth_mm"].max()
ax.set_ylim(lo - 0.05 * (hi - lo), hi + 0.35 * (hi - lo)) # 上に余白を作り、式を置く
ax.set(xlabel="くちばしの長さ (mm)", ylabel="くちばしの深さ (mm)")
ax.legend(loc="lower right", title="種")
plt.show()
```
:::
## シンプソンのパラドックス
3 種をまとめた直線(黒の破線)は **右下がり**(傾き −0.085)なのに、**どの種の中でも右上がり**(傾き 0.18〜0.22)です。
- 種の中では、くちばしが長い個体ほど深い
- しかし、ジェンツーは「長くて浅い」くちばしを持つ種なので、3 種をまとめると右下がりに見える
**群を分けずに回帰直線を引くと、関係の向きまで逆になる** ことがあります([記述統計ハンズオン](/study/descriptive_hands_on/) 第 1 章、[交絡ハンズオン](/study/confounding_hands_on/))。
モデルでは、種を一緒に入れると、種の中での傾きが推定できます。
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
coef(lm(bill_depth_mm ~ bill_length_mm + species, data = pb))
```
## Python(seaborn / matplotlib)
```{pyodide}
smf.ols("bill_depth_mm ~ bill_length_mm + species", data=pb).fit().params
```
:::
種で調整した傾きは **0.20** で、種ごとの傾きに近い値になります。
## 信頼帯と予測帯
`geom_smooth()` や `regplot()` の帯は、**回帰直線(平均)の 95% 信頼区間** です。「新しい 1 羽の値がどこに入りそうか」を示す **予測区間** は、ずっと広くなります。
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
ad <- pb |> filter(species == "Adelie")
f_ad <- lm(bill_depth_mm ~ bill_length_mm, data = ad)
grid <- data.frame(bill_length_mm = seq(min(ad$bill_length_mm), max(ad$bill_length_mm), length.out = 100))
ci <- cbind(grid, predict(f_ad, grid, interval = "confidence"))
pi <- cbind(grid, predict(f_ad, grid, interval = "prediction"))
ggplot(ad, aes(bill_length_mm, bill_depth_mm)) +
geom_ribbon(data = pi, aes(y = fit, ymin = lwr, ymax = upr), fill = "grey85") +
geom_ribbon(data = ci, aes(y = fit, ymin = lwr, ymax = upr), fill = "steelblue", alpha = 0.4) +
geom_line(data = ci, aes(y = fit), colour = "steelblue", linewidth = 1) +
geom_point(alpha = 0.6) +
labs(x = "くちばしの長さ (mm)", y = "くちばしの深さ (mm)",
title = "アデリー:青=直線の 95% 信頼区間、灰色=95% 予測区間")
```
## Python(seaborn / matplotlib)
```{pyodide}
ad = pb[pb["species"] == "Adelie"]
m = smf.ols("bill_depth_mm ~ bill_length_mm", data=ad).fit()
grid = pd.DataFrame({"bill_length_mm": np.linspace(ad["bill_length_mm"].min(), ad["bill_length_mm"].max(), 100)})
pr = m.get_prediction(grid).summary_frame(alpha=0.05) # mean_ci_* が信頼区間、obs_ci_* が予測区間
fig, ax = plt.subplots()
ax.fill_between(grid["bill_length_mm"], pr["obs_ci_lower"], pr["obs_ci_upper"], color="0.85", label="95% 予測区間")
ax.fill_between(grid["bill_length_mm"], pr["mean_ci_lower"], pr["mean_ci_upper"], color="steelblue", alpha=0.4, label="95% 信頼区間")
ax.plot(grid["bill_length_mm"], pr["mean"], color="steelblue", lw=2)
ax.scatter(ad["bill_length_mm"], ad["bill_depth_mm"], s=12, alpha=0.6, color="black")
ax.set(xlabel="くちばしの長さ (mm)", ylabel="くちばしの深さ (mm)", title="アデリー")
ax.legend(loc="lower right")
plt.show()
```
:::
::: {.callout-important}
## この章のまとめ
- 直線は ggplot2 なら `geom_smooth(method = "lm")`(指定しないと曲線)、seaborn なら `regplot()`(帯はブートストラップ)
- 式は **自分で計算して文字列に** する。負の切片の符号に注意
- 注記は **パネルの座標** に置く(ggplot2 は `-Inf`/`Inf` と `hjust`/`vjust`、matplotlib は `transform=ax.transAxes`)
- 上付き・斜体は、R の plotmath(`parse = TRUE`)、matplotlib の mathtext(`$...$`)
- 群ごとの直線と全体の直線は **向きが逆になりうる**(シンプソンのパラドックス)
- 帯は **直線の信頼区間**。個体の値の範囲は **予測区間**
:::