Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format the title of a facet_wrap plot to match the facet strips style?

Tags:

r

ggplot2

I'm trying to format the title of a facet_wrap plot to match the style of the facet strips. In the plot below, I added a title "len", but its formatting doesn't look like that of the facet strips (e.g., 0.5, 1, 2) on the right. How can I make the title look like the facet strips (e.g., gray rectangular box, black outline, centered text across the width of the plot, etc.)?

library(tidyverse)

ToothGrowth |> 
  ggplot(aes(x = dose, y = len)) + 
  geom_boxplot(aes(fill = supp)) +
  labs(title = 'len',
       y = NULL) +
  theme_bw() +
  facet_wrap(~dose, ncol = 1, strip.position = "right")

Created on 2025-04-28 with reprex v2.1.1

like image 944
tassones Avatar asked Nov 18 '25 07:11

tassones


2 Answers

One quick way would be to use facet_grid instead, using that text as your column value.


ToothGrowth |> 
  ggplot(aes(x = dose, y = len)) + 
  geom_boxplot(aes(fill = supp)) +
  labs(y = NULL) +
  theme_bw() +
  facet_grid(dose~"len")

enter image description here

like image 166
Jon Spring Avatar answered Nov 19 '25 21:11

Jon Spring


Personally I would go for facet_grid but another, more laborious option would be to use ggtext::element_textbox:

ToothGrowth |>
  ggplot(aes(x = dose, y = len)) +
  geom_boxplot(aes(fill = supp)) +
  labs(
    title = "len",
    y = NULL
  ) +
  theme_bw() +
  facet_wrap(~dose, ncol = 1, strip.position = "right") +
  theme(
    plot.title = ggtext::element_textbox(
      fill = "grey85",
      color = "grey20",
      linetype = 1,
      linewidth = .25,
      halign = .5,
      width = 1,
      padding = unit(rep(4.4, 4), "pt"),
      margin = margin()
    )
  )

Created on 2025-04-28 with reprex v2.1.1

like image 38
stefan Avatar answered Nov 19 '25 21:11

stefan