---
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-layout}
```{webr}
#| include: false
source("R/setup.R")
library(patchwork)
peng <- penguins |> filter(!is.na(sex)) |>
mutate(種 = factor(species, c("Adelie", "Chinstrap", "Gentoo"), c("アデリー", "ヒゲ", "ジェンツー")))
cols <- c(アデリー = "#E69F00", ヒゲ = "#56B4E9", ジェンツー = "#009E73")
p_sc <- ggplot(peng, aes(flipper_length_mm, body_mass_g, colour = 種)) + geom_point(alpha = 0.7, size = 1.2) +
scale_colour_manual(values = cols) + labs(x = "ひれの長さ (mm)", y = "体重 (g)", colour = "種")
p_box <- ggplot(peng, aes(種, body_mass_g, fill = 種)) + geom_boxplot(outlier.shape = NA, alpha = 0.6) +
scale_fill_manual(values = cols) + labs(x = NULL, y = "体重 (g)", fill = "種")
p_bar <- ggplot(peng, aes(island, fill = 種)) + geom_bar() +
scale_fill_manual(values = cols) + labs(x = "島", y = "羽数", fill = "種")
```
```{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=["アデリー", "ヒゲ", "ジェンツー"])
cols = {"アデリー": "#E69F00", "ヒゲ": "#56B4E9", "ジェンツー": "#009E73"}
```
論文の図は、複数のパネル(A, B, C …)を 1 枚にまとめることがほとんどです。
ファセット(第 3 章)は「同じ形の図を並べる」ものでしたが、ここでは **違う種類の図を自由に配置** します。
## 基本の並べ方
::: {.panel-tabset group="lang"}
## R(ggplot2)
`patchwork` を読み込むと、ggplot の図を **演算子で並べられます**。
| 書き方 | 意味 |
|---|---|
| `p1 + p2` または `p1 \| p2` | 横に並べる |
| `p1 / p2` | 縦に並べる |
| `(p1 \| p2) / p3` | 上に 2 つ、下に 1 つ |
```{webr}
#| fig-width: 9
#| fig-height: 6
(p_sc | p_box) / p_bar +
plot_layout(guides = "collect") + # 凡例を 1 つにまとめる
plot_annotation(tag_levels = "A") # パネルに A, B, C をつける
```
## Python(seaborn / matplotlib)
matplotlib では、`plt.subplot_mosaic()` で、**文字の並びでレイアウトを描く** のが便利です。
```{pyodide}
fig, axd = plt.subplot_mosaic([["A", "B"],
["C", "C"]], figsize=(9, 6), layout="constrained")
sns.scatterplot(data=peng, x="flipper_length_mm", y="body_mass_g", hue="種", palette=cols, s=15, ax=axd["A"], legend=False)
sns.boxplot(data=peng, x="種", y="body_mass_g", hue="種", palette=cols, showfliers=False, ax=axd["B"], legend=False)
sns.countplot(data=peng, x="island", hue="種", palette=cols, ax=axd["C"])
axd["A"].set(xlabel="ひれの長さ (mm)", ylabel="体重 (g)")
axd["B"].set(xlabel="", ylabel="体重 (g)")
axd["C"].set(xlabel="島", ylabel="羽数")
for label, ax in axd.items(): # パネルラベル(A, B, C)
ax.text(-0.02, 1.02, label, transform=ax.transAxes, fontsize=14, fontweight="bold", ha="right", va="bottom")
plt.show()
```
`layout="constrained"` は、軸のラベルや凡例が重ならないように、余白を自動で調整します(`tight_layout()` より賢い)。
:::
::: {.callout-warning}
## `guides = "collect"` でも凡例が 2 つ残るとき
patchwork は、**タイトル・値・記号の形がまったく同じ凡例** だけを 1 つにまとめます。散布図の「点」の凡例と、箱ひげ図・棒グラフの「四角」の凡例は別物として残ります。
凡例の名前(`labs(fill = "種")`)と配色をそろえ、それでも残る凡例は、その図の geom に `show.legend = FALSE` をつけて消します。
:::
## 幅・高さの比を変える
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
#| fig-width: 9
#| fig-height: 4
p_sc + p_box + plot_layout(widths = c(2, 1), guides = "collect") + plot_annotation(tag_levels = "a")
```
## Python(seaborn / matplotlib)
```{pyodide}
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 4), width_ratios=[2, 1], layout="constrained")
sns.scatterplot(data=peng, x="flipper_length_mm", y="body_mass_g", hue="種", palette=cols, s=15, ax=ax1)
sns.boxplot(data=peng, x="種", y="body_mass_g", hue="種", palette=cols, showfliers=False, ax=ax2, legend=False)
ax1.set(xlabel="ひれの長さ (mm)", ylabel="体重 (g)"); ax2.set(xlabel="", ylabel="")
for label, ax in zip("ab", [ax1, ax2]):
ax.text(-0.02, 1.02, label, transform=ax.transAxes, fontsize=14, fontweight="bold", ha="right", va="bottom")
plt.show()
```
:::
## 周辺分布つきの散布図を組み立てる
第 2 章で予告した、散布図の上と右に密度を添える図を、自分で組み立てます。**軸を共有** して、散布図と周辺の図の目盛をそろえるのがポイントです。
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
#| fig-width: 6.5
#| fig-height: 6
top <- ggplot(peng, aes(flipper_length_mm, fill = 種)) + geom_density(alpha = 0.5, colour = NA) +
scale_fill_manual(values = cols) + theme_void() + theme(legend.position = "none")
right <- ggplot(peng, aes(body_mass_g, fill = 種)) + geom_density(alpha = 0.5, colour = NA) +
scale_fill_manual(values = cols) + coord_flip() + theme_void() + theme(legend.position = "none")
top + plot_spacer() + p_sc + right +
plot_layout(ncol = 2, widths = c(4, 1), heights = c(1, 4), guides = "collect") &
theme(legend.position = "bottom")
```
`patchwork` は、パネルの **軸の位置を自動でそろえて** 並べます。`theme_void()` で周辺の図の軸を消し、`plot_spacer()` で右上を空けています。
## Python(seaborn / matplotlib)
```{pyodide}
fig, axd = plt.subplot_mosaic([["top", "."],
["main", "right"]], figsize=(6.5, 6),
width_ratios=[4, 1], height_ratios=[1, 4],
layout="constrained", empty_sentinel=".")
axd["top"].sharex(axd["main"]); axd["right"].sharey(axd["main"]) # 軸を共有して目盛をそろえる
sns.scatterplot(data=peng, x="flipper_length_mm", y="body_mass_g", hue="種", palette=cols, s=15, ax=axd["main"])
sns.kdeplot(data=peng, x="flipper_length_mm", hue="種", palette=cols, fill=True, alpha=0.4, lw=0, legend=False, ax=axd["top"])
sns.kdeplot(data=peng, y="body_mass_g", hue="種", palette=cols, fill=True, alpha=0.4, lw=0, legend=False, ax=axd["right"])
axd["top"].axis("off"); axd["right"].axis("off")
axd["main"].set(xlabel="ひれの長さ (mm)", ylabel="体重 (g)")
plt.show()
```
`"."` を「何も置かない」場所にして、`sharex()`・`sharey()` で周辺の図と散布図の軸を共有しています。
:::
## はめ込み図(インセット)
大きな図の一部を拡大した図や、補足の図を **パネルの中に** 置きます。
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
zoom <- p_sc + coord_cartesian(xlim = c(185, 200), ylim = c(3200, 4200)) +
theme(legend.position = "none", axis.title = element_blank(), plot.background = element_rect(colour = "grey50"))
p_sc + annotate("rect", xmin = 185, xmax = 200, ymin = 3200, ymax = 4200, fill = NA, colour = "grey50") +
inset_element(zoom, left = 0.62, bottom = 0.02, right = 0.99, top = 0.4) # パネルの座標で位置を指定
```
## Python(seaborn / matplotlib)
```{pyodide}
fig, ax = plt.subplots()
sns.scatterplot(data=peng, x="flipper_length_mm", y="body_mass_g", hue="種", palette=cols, s=15, ax=ax)
ins = ax.inset_axes([0.62, 0.05, 0.36, 0.38]) # パネルの座標で [左, 下, 幅, 高さ]
sns.scatterplot(data=peng, x="flipper_length_mm", y="body_mass_g", hue="種", palette=cols, s=15, ax=ins, legend=False)
ins.set(xlim=(185, 200), ylim=(3200, 4200), xlabel="", ylabel="")
ins.tick_params(labelsize=8)
ax.indicate_inset_zoom(ins, edgecolor="0.4") # 拡大した範囲と線で結ぶ
ax.set(xlabel="ひれの長さ (mm)", ylabel="体重 (g)")
ax.legend(loc="upper left")
plt.show()
```
:::
## 第 2 の軸
同じ量を **別の単位** でも示したいとき(g と kg、℃ と ℉)は、第 2 の軸が使えます。
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
p_box + scale_y_continuous(sec.axis = sec_axis(~ . / 453.6, name = "体重 (ポンド)")) +
theme(legend.position = "none")
```
## Python(seaborn / matplotlib)
```{pyodide}
fig, ax = plt.subplots()
sns.boxplot(data=peng, x="種", y="body_mass_g", hue="種", palette=cols, showfliers=False, ax=ax, legend=False)
sec = ax.secondary_yaxis("right", functions=(lambda g: g / 453.6, lambda lb: lb * 453.6)) # 変換と逆変換
sec.set_ylabel("体重 (ポンド)")
ax.set(xlabel="", ylabel="体重 (g)")
plt.show()
```
:::
::: {.callout-warning}
## 違う量を左右の軸に描かない
左右に **違う量**(例:体重と気温)の軸を持つ図は、軸の範囲の選び方しだいで、2 つの線がいくらでも「連動している」ように見せられます。
違う量は、**上下に並べたパネル**(x 軸を共有)で示します。ggplot2 の `sec_axis()` は、わざと **同じ量の変換** しか描けないように作られています。
:::
::: {.callout-important}
## この章のまとめ
- R は `patchwork`(`+`, `|`, `/`、`plot_layout()`、`plot_annotation(tag_levels = "A")`)
- Python は `plt.subplots()`・`plt.subplot_mosaic()`、`layout="constrained"`、パネルラベルは `ax.text(..., transform=ax.transAxes)`
- 周辺分布の図は、**軸を共有**(patchwork は自動、matplotlib は `sharex`/`sharey`)
- はめ込み図は `inset_element()` / `ax.inset_axes()`。第 2 の軸は **同じ量の単位の変換だけ** に使う
:::