boshek
boshek

Reputation: 4406

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.

Upvotes: 3

Views: 566

Answers (1)

Roland
Roland

Reputation: 132706

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)

Upvotes: 6

Related Questions