---
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 >}}
# Assembling multiple panels {#sec-layout}
```{webr}
#| include: false
source("R/setup.R")
library(patchwork)
peng <- penguins |> filter(!is.na(sex)) |>
mutate(Species = factor(species, c("Adelie", "Chinstrap", "Gentoo"), c("Adelie", "Chinstrap", "Gentoo")))
cols <- c(Adelie = "#E69F00", Chinstrap = "#56B4E9", Gentoo = "#009E73")
p_sc <- ggplot(peng, aes(flipper_length_mm, body_mass_g, colour = Species)) + geom_point(alpha = 0.7, size = 1.2) +
scale_colour_manual(values = cols) + labs(x = "Flipper length (mm)", y = "Body mass (g)", colour = "Species")
p_box <- ggplot(peng, aes(Species, body_mass_g, fill = Species)) + geom_boxplot(outlier.shape = NA, alpha = 0.6) +
scale_fill_manual(values = cols) + labs(x = NULL, y = "Body mass (g)", fill = "Species")
p_bar <- ggplot(peng, aes(island, fill = Species)) + geom_bar() +
scale_fill_manual(values = cols) + labs(x = "Island", y = "Count", fill = "Species")
```
```{pyodide}
#| include: false
exec(open("py/setup.py").read())
peng = penguins.dropna(subset=["sex"]).copy()
peng["Species"] = pd.Categorical(peng["species"].map({"Adelie": "Adelie", "Chinstrap": "Chinstrap", "Gentoo": "Gentoo"}),
categories=["Adelie", "Chinstrap", "Gentoo"])
cols = {"Adelie": "#E69F00", "Chinstrap": "#56B4E9", "Gentoo": "#009E73"}
```
Figures in papers almost always combine several panels (A, B, C …) into one.
Facets (Chapter 3) "arrange plots of the same form"; here we **freely place different kinds of plots**.
## Basic arrangement
::: {.panel-tabset group="lang"}
## R (ggplot2)
Once you load `patchwork`, you can **arrange ggplot figures with operators**.
| Syntax | Meaning |
|---|---|
| `p1 + p2` or `p1 \| p2` | Side by side |
| `p1 / p2` | Stacked vertically |
| `(p1 \| p2) / p3` | Two on top, one below |
```{webr}
#| fig-width: 9
#| fig-height: 6
(p_sc | p_box) / p_bar +
plot_layout(guides = "collect") + # merge the legends into one
plot_annotation(tag_levels = "A") # tag the panels A, B, C
```
## Python (seaborn / matplotlib)
In matplotlib, `plt.subplot_mosaic()` is handy: you **draw the layout with a grid of letters**.
```{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="Species", palette=cols, s=15, ax=axd["A"], legend=False)
sns.boxplot(data=peng, x="Species", y="body_mass_g", hue="Species", palette=cols, showfliers=False, ax=axd["B"], legend=False)
sns.countplot(data=peng, x="island", hue="Species", palette=cols, ax=axd["C"])
axd["A"].set(xlabel="Flipper length (mm)", ylabel="Body mass (g)")
axd["B"].set(xlabel="", ylabel="Body mass (g)")
axd["C"].set(xlabel="Island", ylabel="Count")
for label, ax in axd.items(): # panel labels (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"` automatically adjusts the margins so that axis labels and legends don't overlap (smarter than `tight_layout()`).
:::
::: {.callout-warning}
## When two legends remain even with `guides = "collect"`
patchwork merges only legends whose **title, values and key shapes are exactly the same**. The "point" legend of a scatter plot and the "square" legend of a box plot or bar chart remain separate.
Make the legend names (`labs(fill = "Species")`) and colours consistent, and remove any legend that still remains by adding `show.legend = FALSE` to that plot's geom.
:::
## Changing width and height ratios
::: {.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="Species", palette=cols, s=15, ax=ax1)
sns.boxplot(data=peng, x="Species", y="body_mass_g", hue="Species", palette=cols, showfliers=False, ax=ax2, legend=False)
ax1.set(xlabel="Flipper length (mm)", ylabel="Body mass (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()
```
:::
## Assembling a scatter plot with marginal distributions
As promised in Chapter 2, we build ourselves the figure with densities above and to the right of the scatter plot. The key point is to **share the axes** so that the ticks of the scatter plot and the marginal plots line up.
::: {.panel-tabset group="lang"}
## R (ggplot2)
```{webr}
#| fig-width: 6.5
#| fig-height: 6
top <- ggplot(peng, aes(flipper_length_mm, fill = Species)) + 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 = Species)) + 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` arranges panels while **automatically aligning their axes**. `theme_void()` removes the axes of the marginal plots, and `plot_spacer()` leaves the top right empty.
## 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"]) # share axes so the ticks line up
sns.scatterplot(data=peng, x="flipper_length_mm", y="body_mass_g", hue="Species", palette=cols, s=15, ax=axd["main"])
sns.kdeplot(data=peng, x="flipper_length_mm", hue="Species", palette=cols, fill=True, alpha=0.4, lw=0, legend=False, ax=axd["top"])
sns.kdeplot(data=peng, y="body_mass_g", hue="Species", 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="Flipper length (mm)", ylabel="Body mass (g)")
plt.show()
```
`"."` marks a spot where "nothing is placed", and `sharex()` / `sharey()` share the axes between the marginal plots and the scatter plot.
:::
## Inset figures
Place a zoomed-in view of part of a large figure, or a supplementary figure, **inside the panel**.
::: {.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) # position given in panel coordinates
```
## Python (seaborn / matplotlib)
```{pyodide}
fig, ax = plt.subplots()
sns.scatterplot(data=peng, x="flipper_length_mm", y="body_mass_g", hue="Species", palette=cols, s=15, ax=ax)
ins = ax.inset_axes([0.62, 0.05, 0.36, 0.38]) # [left, bottom, width, height] in panel coordinates
sns.scatterplot(data=peng, x="flipper_length_mm", y="body_mass_g", hue="Species", 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") # connect the zoomed region with lines
ax.set(xlabel="Flipper length (mm)", ylabel="Body mass (g)")
ax.legend(loc="upper left")
plt.show()
```
:::
## Secondary axes
When you want to show the same quantity **in another unit** as well (g and kg, °C and °F), you can use a secondary axis.
::: {.panel-tabset group="lang"}
## R (ggplot2)
```{webr}
p_box + scale_y_continuous(sec.axis = sec_axis(~ . / 453.6, name = "Body mass (lb)")) +
theme(legend.position = "none")
```
## Python (seaborn / matplotlib)
```{pyodide}
fig, ax = plt.subplots()
sns.boxplot(data=peng, x="Species", y="body_mass_g", hue="Species", palette=cols, showfliers=False, ax=ax, legend=False)
sec = ax.secondary_yaxis("right", functions=(lambda g: g / 453.6, lambda lb: lb * 453.6)) # transform and inverse
sec.set_ylabel("Body mass (lb)")
ax.set(xlabel="", ylabel="Body mass (g)")
plt.show()
```
:::
::: {.callout-warning}
## Don't plot different quantities on the left and right axes
With a figure that has axes for **different quantities** on the left and right (e.g. body mass and temperature), you can make two lines look "linked" as much as you like, depending on how you choose the axis ranges.
Show different quantities in **panels stacked vertically** (sharing the x-axis). ggplot2's `sec_axis()` is deliberately designed so that it can only draw **a transformation of the same quantity**.
:::
::: {.callout-important}
## Chapter summary
- In R, `patchwork` (`+`, `|`, `/`, `plot_layout()`, `plot_annotation(tag_levels = "A")`)
- In Python, `plt.subplots()` / `plt.subplot_mosaic()`, `layout="constrained"`, and panel labels with `ax.text(..., transform=ax.transAxes)`
- For marginal-distribution figures, **share the axes** (automatic in patchwork, `sharex`/`sharey` in matplotlib)
- Insets with `inset_element()` / `ax.inset_axes()`. Use secondary axes **only for unit conversions of the same quantity**
:::