Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a simple function with ggplot2

I am new to writing functions so it is probably no surprise that I haven't been able to figure this out. I'd just like to generate a simple function whereby one specifies the dataframe and the variable you want then ggplot generates a bivariate plot. I feel like below should work as I've used a couple workarounds suggested for functions with ggplot2:

library(ggplot2)

xy <- data.frame(xvar=1:10,yvar=1:10)

plotfunc <- function(Data, x, y){
  .e <- environment()
  ggplot(Data, aes(x = x, y = y), environment = .e) + 
  geom_line()
}

plotfunc(xy, xvar, yvar)

However, the above code generates this error message:

Error in eval(expr, envir, enclos) : object 'xvar' not found
In addition: Warning message:
In eval(expr, envir, enclos) : restarting interrupted promise evaluation

Any suggestions on what I am doing wrong here? Obviously this is a trivial example and I am hoping to scale this to a broader usage.

Thanks in advance.

like image 826
boshek Avatar asked Sep 20 '26 09:09

boshek


1 Answers

Use aes_q:

plotfunc <- function(Data, x, y){
  print(
    ggplot(Data, aes_q(x = substitute(x), y = substitute(y))) + 
      geom_line()
  )
}

plotfunc(xy, xvar, yvar)
like image 177
Roland Avatar answered Sep 23 '26 00:09

Roland