Home > Mobile >  Using labeller to add units to strip labels with ggplot2 and facet_wrap
Using labeller to add units to strip labels with ggplot2 and facet_wrap

Time:02-01

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)

CodePudding user response:

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")))

CodePudding user response:

I think you would typically modify the dataframe before creating the plot to do that. This might not be what you are looking for but I would think this is the most practical solution

df2 <- 
  df %>%
  mutate(
    group2 = paste(group, "mg")
  )

ggplot(df2)  
  geom_boxplot(aes(y = output))  
  facet_wrap(vars(group2))

CodePudding user response:

You can create your own labeller function, as described here: https://ggplot2.tidyverse.org/reference/labeller.html

For example,

library(ggplot2)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

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

unit_labeller <- function(string) {
  labeled_string <- paste(string, "mg")
  return(labeled_string)
}

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

Created on 2023-01-31 by the reprex package (v2.0.1)

  • Related