Search code examples
rggplot2facet-wrap

Condition facetting of ggplot2 plot


I'm trying to create a univariate distribution plot with ggplot2 that optionally allows us to provide a faceting variable.

My goal is to conditionally create facets for a density plot. Below, I create a function that works with a single unquoted variable. The moment I add an unquoted facetting variable, that variable is unable to be found.

The last line of code below should provide a density plot for gear levels 3, 4, and 5.

library(ggplot2)

# univariate density function w/ conditional facetting
univar_plot <- function(df, var, facet_var = NULL) {
  
  # create density plot
  p <- df |> ggplot(aes(x = {{var}})) + geom_density()

  # Conditional faceting
  if(!is.null(facet_var)) p <- p + facet_wrap(vars( {{facet_var}} ))
  # plot
  p
}

univar_plot(mtcars, mpg) # works
univar_plot(mtcars, mpg, facet_var = gear) # Error: object 'gear' not found

Solution

  • You can get the facets by providing a quoted column name and using get to supply that as a variable to ggplot:

    univar_plot <- function(df, var, facet_var = NULL) {
      
      # create density plot
      p <- df |> ggplot(aes(x = {{var}})) + geom_density()
      
      # Conditional faceting
      if(!is.null(facet_var)) p <- p + facet_wrap(vars(get(facet_var)))
      # plot
      p
    }
    
    univar_plot(mtcars, mpg, facet_var = "gear")
    

    enter image description here

    I'm not sure how to supply it as an unquoted variable - probably something with rlang or quote/substitute