---
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: true
pyodide:
packages: [pandas, matplotlib, seaborn]
cell-options:
autorun: true
---
{{< include ./_extensions/r-wasm/live/_knitr.qmd >}}
# 内部のしくみ:統計変換・軸の範囲・座標変換・描画オブジェクト {#sec-deep}
```{webr}
#| include: false
source("R/setup.R")
pg <- penguins |> filter(!is.na(body_mass_g))
```
```{pyodide}
#| include: false
exec(open("py/setup.py").read())
pg = penguins.dropna(subset=["body_mass_g"]).copy()
```
ここまでの章で「なぜこう書くのか」が気になったところを、内部のしくみから説明します。ここが分かると、思いどおりにならないときに **どこを直せばよいか** が分かります。
## ggplot2 の統計変換:描く前に何が計算されているか
`geom_histogram()`・`geom_boxplot()`・`geom_smooth()` は、データをそのまま描いているのではなく、**統計変換(stat)で要約した結果** を描いています。
`layer_data()` で、実際に描かれる値を取り出せます。
```{webr}
g <- ggplot(pg, aes(species, body_mass_g)) + geom_boxplot()
layer_data(g)[, c("x", "ymin", "lower", "middle", "upper", "ymax")] # 箱ひげ図の 5 つの値
```
```{webr}
h <- ggplot(pg, aes(body_mass_g)) + geom_histogram(binwidth = 250)
head(layer_data(h)[, c("xmin", "xmax", "count", "density")]) # 各ビンの数と密度
```
### `after_stat()`:計算された値を使う
統計変換で計算された値(`count`, `density`, `prop` など)は、`after_stat()` で対応づけに使えます。
```{webr}
ggplot(pg, aes(body_mass_g, fill = species)) +
geom_histogram(aes(y = after_stat(density)), binwidth = 200, alpha = 0.6, position = "identity") + # 数ではなく密度
geom_density(alpha = 0, linewidth = 0.8, aes(colour = species), show.legend = FALSE) +
labs(x = "体重 (g)", y = "密度")
```
```{webr}
ggplot(pg, aes(species, body_mass_g)) +
geom_point(position = position_jitter(width = 0.15, seed = 1), alpha = 0.3) +
stat_summary(fun.data = mean_se, geom = "errorbar", width = 0.2, colour = "firebrick") + # 平均 ± SE を計算して描く
stat_summary(fun = mean, geom = "point", size = 3, colour = "firebrick") +
labs(x = NULL, y = "体重 (g)", caption = "赤:平均 ± SE")
```
## 軸の範囲の罠:`ylim()` と `coord_cartesian()`
箱ひげ図の縦軸を 3000〜5000 g に絞りたいとします。ggplot2 には 2 つの方法があり、**結果が違います**。
```{webr}
library(patchwork)
g1 <- g + labs(title = "そのまま")
g2 <- g + ylim(3000, 5000) + labs(title = "ylim(3000, 5000)")
g3 <- g + coord_cartesian(ylim = c(3000, 5000)) + labs(title = "coord_cartesian(ylim = ...)")
g1 + g2 + g3
```
```{webr}
rbind(そのまま = layer_data(g)$middle,
ylim = suppressWarnings(layer_data(g + ylim(3000, 5000)))$middle,
coord_cartesian = layer_data(g + coord_cartesian(ylim = c(3000, 5000)))$middle)
```
`ylim()`(`scale_y_continuous(limits = )` と同じ)は、範囲の外の **データを捨ててから** 統計変換をします。そのため、ジェンツーの **中央値が 5000 から 4700 に変わって** しまいました。
`coord_cartesian()` は、計算が終わった図を **拡大して見せるだけ** なので、中央値は変わりません。
「Removed n rows containing non-finite values」という警告は、データが捨てられたサインです。**範囲を絞るときは `coord_cartesian()`** を使います。
::: {.callout-note}
## matplotlib・seaborn では
matplotlib の `ax.set_ylim()` は、描いた後の **表示範囲** を変えるだけなので、`coord_cartesian()` と同じです。
同じ間違いが起きるのは、**描く前にデータを絞り込んだとき**(`df[df.y < 5000]` で描くなど)です。
:::
## matplotlib の座標変換:テキストをどこに置くか
matplotlib のすべての描画は、**座標変換(transform)** によって、指定した値を画面の位置に変換しています。主なものは 4 つです。
| 座標 | 指定 | (0, 0) と (1, 1) | 使いどころ |
|---|---|---|---|
| データ | `ax.transData`(既定) | 軸の値そのもの | 点・線・データに結びついた注記 |
| パネル | `ax.transAxes` | パネルの左下・右上 | 式・パネルラベル・凡例の位置 |
| 図全体 | `fig.transFigure` | 図の左下・右上 | 図全体の見出し・注釈 |
| 混合 | `ax.get_xaxis_transform()` | x はデータ、y はパネル | 縦線のラベルを、いつもパネルの上端に |
```{pyodide}
fig, ax = plt.subplots()
sns.histplot(data=pg, x="body_mass_g", binwidth=200, color="0.7", ax=ax)
m = pg["body_mass_g"].mean()
ax.axvline(m, color="firebrick")
# x はデータの値(平均)、y はパネルの上端から少し下 → 縦軸の範囲が変わっても上端に置かれる
ax.text(m, 0.97, f" 平均 {m:.0f} g", transform=ax.get_xaxis_transform(), color="firebrick", va="top")
ax.text(0.98, 0.97, "パネルの座標 (0.98, 0.97)", transform=ax.transAxes, ha="right", va="top", fontsize=9)
fig.text(0.01, 0.01, "図全体の座標 (0.01, 0.01)", fontsize=9, color="0.4")
ax.annotate("点からのずれ(ポイント)", xy=(6000, 5), xytext=(-60, 40), textcoords="offset points",
arrowprops=dict(arrowstyle="->"), fontsize=9)
ax.set(xlabel="体重 (g)", ylabel="羽数")
plt.show()
```
ggplot2 には座標変換を直接指定するしくみはありませんが、`x = -Inf`/`Inf`(パネルの端)と `hjust`/`vjust` の組み合わせで、パネルの座標に近いことができます(第 6 章)。
## matplotlib の描画オブジェクト:描いた後に変える
matplotlib の図は、**Figure → Axes → 線・点・四角・文字** という、オブジェクト(Artist)の木でできています。
seaborn で描いた図も、この木を探れば、後から 1 つずつ変更できます。
```{pyodide}
fig, ax = plt.subplots()
sns.boxplot(data=pg, x="species", y="body_mass_g", ax=ax)
print("四角(箱):", len(ax.patches), " 線:", len(ax.lines), " 点の集まり:", len(ax.collections))
# 箱の塗りを後から変える・ハッチ(斜線)をつける
for patch, color, hatch in zip(ax.patches, ["#E69F00", "#56B4E9", "#009E73"], ["", "//", ".."]):
patch.set_facecolor(color); patch.set_alpha(0.6); patch.set_hatch(hatch)
ax.set(xlabel="", ylabel="体重 (g)")
plt.show()
```
::: {.callout-tip}
## 重なり順(zorder)と、はみ出し(clip_on)
- `zorder=`:大きいほど手前に描かれる。目盛線を点の後ろに、注記を一番前に
- `clip_on=False`:パネルの外にはみ出して描く(パネルの外に置く記号・ラベル)
:::
## 凡例を自分で作る
凡例に、データにない要素(「黒の破線:全体の回帰直線」など)を載せたいことがあります。
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
ggplot(pg, aes(flipper_length_mm, body_mass_g)) +
geom_point(aes(colour = species), alpha = 0.5) +
geom_smooth(aes(linetype = "全体の回帰直線"), method = "lm", formula = y ~ x, se = FALSE, colour = "black") +
scale_linetype_manual(name = NULL, values = c("全体の回帰直線" = 2)) + # 線の種類の凡例を作る
guides(colour = guide_legend(override.aes = list(alpha = 1, size = 3))) + # 凡例の点だけ濃く大きく
labs(x = "ひれの長さ (mm)", y = "体重 (g)", colour = "種")
```
ggplot2 では、**定数を `aes()` に入れて** 凡例を作り(第 2 章では誤りとして紹介した書き方を、わざと使う)、`scale_xxx_manual()` で見た目を決めます。
`guides(... override.aes = )` は、図の点は薄いまま、**凡例の記号だけ** を変えます。
## Python(seaborn / matplotlib)
```{pyodide}
from matplotlib.lines import Line2D
fig, ax = plt.subplots()
sns.scatterplot(data=pg, x="flipper_length_mm", y="body_mass_g", hue="species", alpha=0.5, ax=ax)
sns.regplot(data=pg, x="flipper_length_mm", y="body_mass_g", scatter=False, ci=None,
line_kws={"color": "black", "ls": "--"}, ax=ax)
handles, labels = ax.get_legend_handles_labels() # seaborn が作った凡例の要素
handles.append(Line2D([], [], color="black", ls="--")) # 自分で要素を足す
labels.append("全体の回帰直線")
for h in handles[:3]:
h.set_alpha(1) # 凡例の点だけ濃く
ax.legend(handles, labels, loc="upper left")
ax.set(xlabel="ひれの長さ (mm)", ylabel="体重 (g)")
plt.show()
```
matplotlib の凡例は、**記号(handle)と文字(label)のリスト** です。`Line2D` などで、図にない記号も自由に作れます。
:::
## seaborn.objects:Python で「文法」を使う
seaborn 0.12 から、ggplot2 と同じ **グラフィックスの文法** の考え方で書ける `seaborn.objects` が加わりました。
```{pyodide}
import seaborn.objects as so
(
so.Plot(pg.dropna(subset=["bill_length_mm", "bill_depth_mm"]),
x="bill_length_mm", y="bill_depth_mm", color="species")
.add(so.Dot(alpha=0.5)) # 幾何:点
.add(so.Line(), so.PolyFit(order=1)) # 幾何:線、統計:1 次の多項式(直線)
.label(x="くちばしの長さ (mm)", y="くちばしの深さ (mm)", color="種")
.layout(size=(7, 4.2))
.show()
)
```
```{pyodide}
(
so.Plot(pg, x="species", y="body_mass_g", color="sex")
.add(so.Dot(pointsize=3, alpha=0.4), so.Jitter(0.3), so.Dodge()) # ずらして点
.add(so.Range(), so.Est(errorbar="sd"), so.Dodge()) # 平均 ± SD
.add(so.Dot(pointsize=8), so.Agg(), so.Dodge()) # 平均
.label(x="", y="体重 (g)", color="性別")
.layout(size=(7, 4.2))
.show()
)
```
| ggplot2 | seaborn.objects |
|---|---|
| `ggplot(data, aes(x, y, colour))` | `so.Plot(data, x=, y=, color=)` |
| `+ geom_point()` | `.add(so.Dot())` |
| `+ geom_smooth(method = "lm")` | `.add(so.Line(), so.PolyFit(1))` |
| `position_jitter` / `position_dodge` | `so.Jitter()` / `so.Dodge()` |
| `stat_summary()` | `so.Agg()`, `so.Est()` |
| `facet_wrap(~ v)` | `.facet(col=)` |
| `labs()` | `.label()` |
まだ機能は ggplot2 ほど多くありませんが、**同じ考え方で両方の言語を書ける** のが利点です。
R の文法を Python でそのまま使いたいなら、ggplot2 をほぼそのまま移植した **plotnine** というライブラリもあります(このページのブラウザの Python には入っていません)。
## 関数にして使い回す
同じ形の図を何度も作るなら、関数にします。ggplot2 では、**列名を文字列で受け取り `.data[[ ]]` で使う** のが分かりやすい方法です。
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
box_with_points <- function(d, group, value, ylab = value) {
ggplot(d, aes(.data[[group]], .data[[value]], colour = .data[[group]])) +
geom_boxplot(outlier.shape = NA, width = 0.5) +
geom_point(position = position_jitter(width = 0.12, height = 0, seed = 1), alpha = 0.4) +
theme(legend.position = "none") +
labs(x = NULL, y = ylab)
}
box_with_points(pg, "species", "flipper_length_mm", "ひれの長さ (mm)") +
box_with_points(pg, "island", "body_mass_g", "体重 (g)")
```
## Python(seaborn / matplotlib)
```{pyodide}
def box_with_points(d, group, value, ylab=None, ax=None):
ax = ax or plt.gca()
sns.boxplot(data=d, x=group, y=value, hue=group, showfliers=False, width=0.5, fill=False, legend=False, ax=ax)
np.random.seed(1)
sns.stripplot(data=d, x=group, y=value, hue=group, jitter=0.12, alpha=0.4, legend=False, ax=ax)
ax.set(xlabel="", ylabel=ylab or value)
return ax # 軸を返すと、後から調整できる
fig, axes = plt.subplots(1, 2, figsize=(10, 4), layout="constrained")
box_with_points(pg, "species", "flipper_length_mm", "ひれの長さ (mm)", ax=axes[0])
box_with_points(pg, "island", "body_mass_g", "体重 (g)", ax=axes[1])
plt.show()
```
matplotlib の関数は、**`ax=` を受け取り `ax` を返す** 形にすると、どのレイアウトにも組み込めます(seaborn の軸レベルの関数と同じ設計)。
:::
::: {.callout-important}
## この章のまとめ
- ggplot2 の geom の多くは **統計変換** の結果を描く。`layer_data()` で中身を見られ、`after_stat()` で使える
- **`ylim()` はデータを捨ててから計算する**。範囲を絞るのは `coord_cartesian()`(matplotlib の `set_ylim()` は表示だけ)
- matplotlib は **座標変換** を使い分ける:データ・パネル(`transAxes`)・図全体・混合
- matplotlib の図は **Artist の木**。seaborn の出力も後から 1 つずつ変更できる。凡例は handle と label のリスト
- `seaborn.objects` は Python の文法。関数にするときは、R は `.data[[ ]]`、Python は `ax=` を受け取って返す
:::