Skip to content

Instantly share code, notes, and snippets.

@z3tt
Last active December 22, 2025 08:58
Show Gist options
  • Select an option

  • Save z3tt/2cbd07f018272716e6759811064218f2 to your computer and use it in GitHub Desktop.

Select an option

Save z3tt/2cbd07f018272716e6759811064218f2 to your computer and use it in GitHub Desktop.
Place Striptext inside Facet Panels with ggplot2
library(ggplot2)
gm_2023 <- readr::read_csv("https://www.cedricscherer.com/data/gapminder-2023.csv")
pal <- c(Africa = "#00D9EE", Americas = "#4CF101", Asia = "#FF4670", Europe = "#FFE702", Oceania = "#CA4ADC")
# base plot
g <-
ggplot(gm_2023, aes(x = gdp_pcap, y = life_exp, size = pop)) +
geom_point(
color = "white",
layout = "fixed"
) +
geom_point(
shape = 21, fill = "grey65", color = "white", alpha = .3,
layout = "fixed"
) +
geom_point(
shape = 21, aes(fill = continent), alpha = .7, stroke = .7
) +
scale_x_log10(
labels = scales::label_dollar(),
name = "GDP per capita (int$, log scale)",
breaks = 1000 * 2^(-1:7)
) +
scale_y_continuous(
breaks = seq(30, 90, by = 5), name = "Life expectancy in years",
expand = expansion(add = c(2, 3))
) +
scale_fill_manual(
values = pal, guide = "none"
) +
scale_size(
range = c(.8, 20),
breaks = 1 * 10^(6:9),
labels = c("1M", "10M", "100M", "1 billion\nhumans"),
name = "Area by Population:",
guide = guide_legend(override.aes = list(fill = "#9FBBC1"))
) +
facet_wrap(~continent, nrow = 5) +
theme_bw(base_family = "Atkinson Hyperlegible") +
theme(
panel.grid.minor = element_blank(),
panel.spacing = unit(1, "lines"),
plot.margin = margin_auto(12),
legend.justification = "top",
legend.box.margin = margin_part(t = 40),
axis.title.x = element_text(hjust = 0, margin = margin_part(t = 12)),
axis.title.y = element_text(hjust = .98, margin = margin_part(r = 12)),
strip.background = element_blank(),
strip.text = element_text(face = "bold", hjust = 0, size = rel(1.4))
)
g
# labels disappear if strip.clip is "on" (default behavior)
g + theme(strip.text = element_text(margin = margin_part(b = -20, l = 8)))
# turn off striptext clipping (and adjust spacings)
g +
theme(
strip.text = element_text(margin = margin_part(b = -20, l = 8)),
strip.clip = "off",
panel.spacing = unit(2, "lines"),
plot.margin = margin(t = 24, r = 12, b = 12, l = 12)
)
# version with geom_label() instead
g +
geom_label(
aes(label = continent, x = 350, y = 81),
stat = "unique", size = 5, hjust = 0,
family = "Atkinson Hyperlegible", fontface = "bold"
) +
theme(
strip.text = element_blank()
)
# version with colored labels
g +
geom_text(
aes(label = continent, x = 350, y = 82.5,
# hacky trick to avoid specfying color scale
fill = continent, color = after_scale(colorspace::darken(fill, .35))),
stat = "unique", size = 5, hjust = 0,
family = "Atkinson Hyperlegible", fontface = "bold"
) +
theme(
strip.text = element_blank()
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment