Arrange plots with tables

R
ggplot
Published

September 22, 2024

I use patchwork regularly to combine ggplots; see my R template.

The recent v1.3 release of patchwork allows adding gt tables.

Tables with short descriptive information are an essential element of my notebooks. So far, I have mainly relied on the default knitr for simple tables and used reactable for larger interactive tables.

So here is an example of patchwork that combines a figure and a gt table, using the palmerpenguins data.

Code
library(tidyverse)
library(patchwork)
library(gt)

library(palmerpenguins)

pg <-
  penguins %>%
  group_by(species) |>
  summarise(
    n = n(),
    bill = mean(bill_length_mm, na.rm = TRUE),
    flipper = mean(flipper_length_mm, na.rm = TRUE)
  )

pl1 <-
  ggplot(penguins, aes(x = flipper_length_mm, y = bill_length_mm, color = factor(species))) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) +
  theme(legend.position = "none")

gt1 <-
  gt(pg) |>
  tab_header(title = "Length mean (mm)") |>
  fmt_number(
    columns = c(bill, flipper),
    decimals = 1
  )

pl1 + gt1