Home > Software engineering >  how to enquote variable names in r ggplot wrappers
how to enquote variable names in r ggplot wrappers

Time:10-29

I would like to write custom wrappers for facets in ggplot and have problems handling variable names.

What I would like to achieve:

mtcars %>% 
  ggplot()   
  ggh4x::facet_manual(vars(cyl %>% 
                             recode('4' = "four", '6' = "six", '8' = "eight") %>% 
                             factor(levels = c("four", "six", "eight"))), 
                      design = matrix(c(1, 1, 2, 3), byrow = TRUE, nrow = 2), 
                      scales = "free")   
  geom_point(aes(x = disp, y = hp))

Now I would like to build a wrapper around this complex facet formula:

my_facet <- function(x) {
  ggh4x::facet_manual(vars(x %>% 
                             recode('4' = "four", '6' = "six", '8' = "eight") %>% 
                             factor(levels = c("four", "six", "eight"))), 
                      design = matrix(c(1, 1, 2, 3), byrow = TRUE, nrow = 2), 
                      scales = "free") 
}

mtcars %>% 
  ggplot()   
  my_facet(x)   
  geom_point(aes(x = disp, y = hp))

But since x is not in the environment but in mtcars, this does not work:

Error in recode(., `4` = "four", `6` = "six", `8` = "eight") : 
  object 'x' not found

I have tried several tricks that change x in the my_facet function, such as sym(x), !!sym(x), enquo(x), {{x}}, but nothing works.

What kind of variable handling is required here?

CodePudding user response:

This works for me. Is the idea you want to reference a variable x <- "cyl" in the global environment?

my_facet <- function(x) {
  ggh4x::facet_manual(vars( {{x}} %>% 
                             recode('4' = "four", '6' = "six", '8' = "eight") %>% 
                             factor(levels = c("four", "six", "eight"))), 
                      design = matrix(c(1, 1, 2, 3), byrow = TRUE, nrow = 2), 
                      scales = "free") 
}

mtcars %>% 
  ggplot()   
  my_facet(cyl)   
  geom_point(aes(x = disp, y = hp))
  • Related