Search code examples
rfunctionggplot2eval

R passing a function argument to ggplot


I'm trying to pass a function argument (or parameter) to a ggplot - here's a dummy dataset to show/ test

test <- data.frame(id=c(1,2,3,4,5), 
                   base=c(230,365,390,201,298), 
                   heig=c(200,310,90,100, 91), 
                   widt=c(21,75,22,46,51))

fun1 <- function(va1,va2){
  ggplot(data=test,mapping=aes(va1, va2)) + geom_point()
}

fun1(base,heig)

I get an error:

Error in `geom_point()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 1st layer.
Caused by error in `FUN()`:
! object 'base' not found
Run `rlang::last_trace()` to see where the error occurred.

I tried {{}}, [[]] and other combinations inside the ggplot in order to call the function param to no avail.


Solution

  • You can use enquo like so:

    library(ggplot2)
    library(rlang)
    
    fun1 <- function(va1,va2) {
      va1 <- enquo(va1)
      va2 <- enquo(va2)
    
      ggplot2::ggplot(data=test,mapping=aes(!!va1, !!va2)) + 
        geom_point()
    }
    

    From the help page of the "Tidy eval helpers":

    (You can find it with: ?enquo):

    enquo() and enquos() delay the execution of one or several function arguments. The former returns a single expression, the latter returns a list of expressions. Once defused, expressions will no longer evaluate on their own. They must be injected back into an evaluation context with ⁠!!⁠ (for a single expression) and ⁠!!!⁠ (for a list of expressions).