Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading