passing parameters to ggplot

One solution would be to pass x and y as string names of columns in data frame DS.

f <- function(DS, x, y) {    
  ggplot(DS, aes_string(x = x, y = y)) + geom_point()  
}

And then call the function as:

f(cars, "speed", "dist")

However, it seems that you don't want that? Can you provide an example why you would need different functionality? Is it because you don't want to have the arguments in the same data frame?


I think it's possible the following type of codes, which only build the aes component.

require(ggplot2)

DS <- data.frame(speed=rnorm(10), dist=rnorm(10))

f <- function(DS, x, y, geom, opts=NULL) {
  aes <- eval(substitute(aes(x, y),
    list(x = substitute(x), y = substitute(y))))
  p <- ggplot(DS, aes) + geom + opts
}

p <- f(DS, speed, dist, geom_point())
p

However, it seems to be complicated approach.

Tags:

R

Ggplot2