Search code examples
rggplot2facet-wrap

Using labeller to add units to strip labels with ggplot2 and facet_wrap


I am making faceted plots in ggplot2. The groups I am faceting by have names that should logically include units, and I'd like to automatically add these units to the strip labels without manually writing out a new vector with all the labels - i.e. replace labels of "1", "2", "3" with "1 mg", "2 mg", "3 mg". I was able to do this using code analogous to the simplified example below. But it's still a little clunky to have to define the label vector separately and I'm wondering if anyone knows of a way to do this within the labeller function itself? It seems like this would be a fairly common scenario so I was surprised not to find more examples of how others have done it online. Thanks in advance!

df <- tibble(
  group = factor(rep(1:3, times = 5)),
  output = sample(1:10, 15, replace = TRUE)
  )

labs <- paste(levels(df$group), "mg")
names(labs) <- levels(df$group)

df %>%
  ggplot()+
  geom_boxplot(aes(y = output))+
  facet_wrap(vars(group), labeller = labeller(group = labs)

Solution

  • Using a lambda or anonymous function in labeller you could do:

    library(ggplot2)
    
    ggplot(df) +
      geom_boxplot(aes(y = output))+
      facet_wrap(vars(group), labeller = labeller(group = ~ paste(.x, "mg")))