简体   繁体   中英

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

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM