Fredrik Nylén
Fredrik Nylén

Reputation: 577

Ability to specify ggplot aesthetics to function that should return a ggplot object

I'm trying to contstuct a function that behaves like a ggplot function, and also returns a ggplot object that other functions may work on further (add facets, apply a theme, etc.).

The hurdle I am facing now is that I cannot get argument passning to the function to work like I would expect it to.

data(iris)
te <- function(data,x,y){

  g <- ggplot(data,aes_q(x=quote(x),y=quote(y))) + scale_x_continuous() + 
  scale_y_continuous() + geom_point()
  return(g)

}
te(iris,x=Species,y=Petal.Length)

What I get then is:

Error: geom_point requires the following missing aesthetics: x, y

I hoped that this would enable me to pass the arguments not as strings, but obviously I am doing something wrong here. The odd thing, for me, is that geom_point is the function that is complaining. How come?

Upvotes: 2

Views: 307

Answers (2)

LyzandeR
LyzandeR

Reputation: 37879

Inside a function you need to use substitute instead of quote:

data(iris)
te <- function(data,x,y){
  
  x <- substitute(x)
  y <- substitute(y)
  g <- ggplot(data,aes_q(x=x,y=y)) + scale_x_discrete() + 
    scale_y_continuous() + geom_point()
  return(g)
  
}
te(iris,x=Species,y=Petal.Length)

This will work perfect.

P.S. I changed scale_x_continuous to scale_x_discrete because Species is discrete

enter image description here

Upvotes: 2

lukeA
lukeA

Reputation: 54237

Try quote when calling the function:

data(iris)
library(ggplot2)
te <- function(data,x,y){
  g <- ggplot(data,aes_q(x,y)) + scale_x_continuous() + 
    scale_y_continuous() + geom_point()
  return(g)

}
te(iris,x=quote(Species),y=quote(Petal.Length))

Upvotes: 2

Related Questions