---
webr:
packages: [dplyr, ggplot2, ggrepel, MASS]
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-scatter}
```{webr}
#| include: false
source("R/setup.R")
```
```{pyodide}
#| include: false
exec(open("py/setup.py").read())
```
## 対応づけ(mapping)と設定(setting)
ggplot2 でいちばん多いつまずきが、**「すべての点を青にしたい」のに `aes()` の中に色を書いてしまう** ことです。
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
# 誤り:aes() の中に定数を書くと、"blue" という名前の「群」ができる
ggplot(penguins, aes(flipper_length_mm, body_mass_g, colour = "blue")) + geom_point()
```
```{webr}
# 正しい:変数と関係ない見た目は aes() の外(geom の引数)に書く
ggplot(penguins, aes(flipper_length_mm, body_mass_g)) + geom_point(colour = "steelblue")
```
## Python(seaborn / matplotlib)
```{pyodide}
fig, axes = plt.subplots(1, 2, figsize=(9, 3.6))
# hue= は「列」との対応づけ、color= は全体の色の設定
sns.scatterplot(data=penguins, x="flipper_length_mm", y="body_mass_g", hue="species", ax=axes[0])
sns.scatterplot(data=penguins, x="flipper_length_mm", y="body_mass_g", color="steelblue", ax=axes[1])
axes[0].set_title("hue=\"species\"(対応づけ)")
axes[1].set_title("color=\"steelblue\"(設定)")
plt.tight_layout()
plt.show()
```
:::
- **対応づけ**:データの列の値によって変わる見た目 → ggplot2 は `aes()` の中、seaborn は `hue=`, `size=`, `style=`
- **設定**:すべての点で同じ見た目 → ggplot2 は `geom_xxx()` の引数、seaborn / matplotlib は `color=`, `s=`, `marker=`
## 配色:両方の言語で同じ色を使う
既定の配色は、R と Python で違います。発表や論文で両方の図を混ぜるなら、**色を自分で決めて両方で使う** のが確実です。
ここでは、色覚の多様性に配慮した **Okabe-Ito の配色** から 3 色を選びます。
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
sp_cols <- c(Adelie = "#E69F00", Chinstrap = "#56B4E9", Gentoo = "#009E73")
ggplot(penguins, aes(flipper_length_mm, body_mass_g, colour = species)) +
geom_point(size = 2) +
scale_colour_manual(values = sp_cols) +
labs(x = "ひれの長さ (mm)", y = "体重 (g)", colour = "種")
```
## Python(seaborn / matplotlib)
```{pyodide}
sp_cols = {"Adelie": "#E69F00", "Chinstrap": "#56B4E9", "Gentoo": "#009E73"}
fig, ax = plt.subplots()
sns.scatterplot(data=penguins, x="flipper_length_mm", y="body_mass_g",
hue="species", palette=sp_cols, s=30, ax=ax)
ax.set(xlabel="ひれの長さ (mm)", ylabel="体重 (g)")
ax.legend(title="種")
plt.show()
```
:::
色を **名前つき**(種の名前 → 色)で指定すると、データの中の順番やファセットで一部の種がいなくても、**同じ種は必ず同じ色** になります。
### 連続量の色:viridis
連続量を色に対応づけるときは、明るさが一様に変わり、白黒印刷でも順番が分かる **viridis** 系の配色が無難です。
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
ggplot(penguins, aes(bill_length_mm, bill_depth_mm, colour = body_mass_g)) +
geom_point(size = 2) +
scale_colour_viridis_c(name = "体重 (g)") +
labs(x = "くちばしの長さ (mm)", y = "くちばしの深さ (mm)")
```
## Python(seaborn / matplotlib)
```{pyodide}
fig, ax = plt.subplots()
sc = ax.scatter(penguins["bill_length_mm"], penguins["bill_depth_mm"],
c=penguins["body_mass_g"], cmap="viridis", s=20)
fig.colorbar(sc, ax=ax, label="体重 (g)")
ax.set(xlabel="くちばしの長さ (mm)", ylabel="くちばしの深さ (mm)")
plt.show()
```
:::
::: {.callout-warning}
## 虹色(jet, rainbow)は避ける
虹色の配色は、明るさが一様でないため、黄色や水色のあたりに **実際にはない境界** が見えてしまいます。連続量には viridis 系、正負に分かれる量(相関係数、差)には中央が白の発散型(`RdBu` など)を使います。
:::
## 点が重なるとき:1 万人の散布図
NHANES の 20 歳以上 1 万人あまりの、身長と体重です。そのまま描くと、真ん中が塗りつぶされて **どこに人が多いのか分かりません**。
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
ggplot(nhanes, aes(Height, Weight)) + geom_point() +
labs(x = "身長 (cm)", y = "体重 (kg)", title = "そのまま")
```
```{webr}
# 1. 小さく・透明に
ggplot(nhanes, aes(Height, Weight)) + geom_point(size = 0.5, alpha = 0.1) +
labs(x = "身長 (cm)", y = "体重 (kg)", title = "小さく・透明に")
```
```{webr}
# 2. 区画ごとに数える(2 次元ヒストグラム)
ggplot(nhanes, aes(Height, Weight)) + geom_bin_2d(bins = 50) +
scale_fill_viridis_c(name = "人数") +
labs(x = "身長 (cm)", y = "体重 (kg)", title = "区画ごとの人数")
```
```{webr}
# 3. 等高線(2 次元の密度)を重ねる
ggplot(nhanes, aes(Height, Weight, colour = Gender)) +
geom_point(size = 0.4, alpha = 0.08) +
geom_density_2d(bins = 6) +
labs(x = "身長 (cm)", y = "体重 (kg)", colour = "性別", title = "密度の等高線")
```
## Python(seaborn / matplotlib)
```{pyodide}
fig, axes = plt.subplots(1, 3, figsize=(12, 3.8), sharex=True, sharey=True)
axes[0].scatter(nhanes["Height"], nhanes["Weight"])
axes[0].set_title("そのまま")
axes[1].scatter(nhanes["Height"], nhanes["Weight"], s=2, alpha=0.1)
axes[1].set_title("小さく・透明に")
hb = axes[2].hexbin(nhanes["Height"], nhanes["Weight"], gridsize=45, cmap="viridis", mincnt=1)
fig.colorbar(hb, ax=axes[2], label="人数")
axes[2].set_title("六角形の区画ごとの人数")
for a in axes:
a.set_xlabel("身長 (cm)")
axes[0].set_ylabel("体重 (kg)")
plt.tight_layout()
plt.show()
```
```{pyodide}
fig, ax = plt.subplots()
sns.scatterplot(data=nhanes, x="Height", y="Weight", hue="Gender", s=3, alpha=0.1, legend=False, ax=ax)
sample = nhanes.dropna(subset=["Height", "Weight"]).sample(3000, random_state=1) # 密度の推定は一部の人で(速さのため)
sns.kdeplot(data=sample, x="Height", y="Weight", hue="Gender", levels=6, ax=ax)
ax.set(xlabel="身長 (cm)", ylabel="体重 (kg)", title="密度の等高線")
plt.show()
```
:::
## 点にラベルをつける
各種で **いちばん重いペンギン** にだけ、体重のラベルをつけます。ラベルが点や他のラベルと重ならないように置くのは、意外に難しい作業です。
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
library(ggrepel)
heaviest <- penguins |> filter(!is.na(body_mass_g)) |>
group_by(species) |> slice_max(body_mass_g, n = 1, with_ties = FALSE)
ggplot(penguins, aes(flipper_length_mm, body_mass_g, colour = species)) +
geom_point(alpha = 0.6) +
geom_point(data = heaviest, size = 3, shape = 21, fill = "white", stroke = 1.5) +
geom_label_repel(data = heaviest, aes(label = paste0(species, " ", body_mass_g, " g")),
show.legend = FALSE, min.segment.length = 0, box.padding = 0.6) +
labs(x = "ひれの長さ (mm)", y = "体重 (g)", colour = "種")
```
`ggrepel` の `geom_text_repel()` / `geom_label_repel()` は、ラベルどうしや点と重ならない位置を自動で探し、必要なら引き出し線を引きます。
## Python(seaborn / matplotlib)
```{pyodide}
heaviest = penguins.dropna(subset=["body_mass_g"]).loc[lambda d: d.groupby("species")["body_mass_g"].idxmax()]
fig, ax = plt.subplots()
sns.scatterplot(data=penguins, x="flipper_length_mm", y="body_mass_g", hue="species", alpha=0.6, ax=ax)
offsets = {"Adelie": (-70, 15), "Chinstrap": (-60, 30), "Gentoo": (-110, -10)} # 点からのずらし量(ポイント)
for _, r in heaviest.iterrows():
ax.annotate(f"{r.species} {r.body_mass_g:.0f} g",
xy=(r.flipper_length_mm, r.body_mass_g), # 指す点(データ座標)
xytext=offsets[r.species], textcoords="offset points", # 文字の位置(点からのずれ)
arrowprops=dict(arrowstyle="-", color="grey"),
bbox=dict(boxstyle="round", fc="white", ec="grey"))
ax.set(xlabel="ひれの長さ (mm)", ylabel="体重 (g)")
plt.show()
```
matplotlib の `ax.annotate()` は、**指す点(`xy`)と文字の位置(`xytext`)を別々に** 指定できます。`textcoords="offset points"` にすると、点からのずれをポイント単位で指定でき、軸の範囲が変わってもずれません。
自動で重なりを避けるには、`adjustText` パッケージを使います(ブラウザの Python には入っていません)。
:::
## 周辺分布をつける
散布図の上と右に、それぞれの変数の分布を添えると、2 変数の関係と 1 変数の分布を同時に見られます。
::: {.panel-tabset group="lang"}
## R(ggplot2)
```{webr}
# ggplot2 では、軸に沿った「ラグ」(細い線)で分布を示すのが手軽
ggplot(penguins, aes(bill_length_mm, bill_depth_mm, colour = species)) +
geom_point(alpha = 0.7) +
geom_rug(alpha = 0.4, length = unit(0.02, "npc")) +
labs(x = "くちばしの長さ (mm)", y = "くちばしの深さ (mm)", colour = "種")
```
ヒストグラムや密度を周辺に並べるには、第 8 章の `patchwork` で図を組み合わせます。
## Python(seaborn / matplotlib)
```{pyodide}
g = sns.jointplot(data=penguins, x="bill_length_mm", y="bill_depth_mm", hue="species", height=5)
g.set_axis_labels("くちばしの長さ (mm)", "くちばしの深さ (mm)")
plt.show()
```
seaborn の `jointplot()` は、散布図と周辺の分布を 1 行で描きます(図レベルの関数)。
:::
::: {.callout-important}
## この章のまとめ
- **対応づけ**(列の値で変わる:`aes()` の中・`hue=`)と **設定**(全体で同じ:`aes()` の外・`color=`)を区別する
- 色は **名前つきで自分で決めて** 両方の言語で使う。連続量は viridis、虹色は避ける
- 点が多いときは、**小さく・透明に**、**区画ごとに数える**、**等高線**
- ラベルは R なら `ggrepel`、Python なら `ax.annotate()`(`xy` と `xytext` を分ける)
:::