Addressing x and y in aes by variable number

I strongly suggest using aes_q instead of passing vectors to aes (@Arun's answer). It may look a bit more complicated, but it is more flexible, when e.g. updating the data.

showplot1 <- function(indata, inx, iny){
  p <- ggplot(indata, 
              aes_q(x = as.name(names(indata)[inx]), 
                    y = as.name(names(indata)[iny])))
  p + geom_point(size=4, alpha = 0.5)
}

And here's the reason why it is preferable:

# test data (using non-standard names)
testdata<-data.frame(v1=rnorm(100), v2=rnorm(100), v3=rnorm(100), v4=rnorm(100), v5=rnorm(100))
names(testdata) <- c("a-b", "c-d", "e-f", "g-h", "i-j")
testdata2 <- data.frame(v1=rnorm(100), v2=rnorm(100), v3=rnorm(100), v4=rnorm(100), v5=rnorm(100))
names(testdata2) <- c("a-b", "c-d", "e-f", "g-h", "i-j")

# works
showplot1(indata=testdata, inx=2, iny=3)
# this update works in the aes_q version
showplot1(indata=testdata, inx=2, iny=3) %+% testdata2

Note: As of ggplot2 v2.0.0 aes_q() has been replaced with aes_() to be consistent with SE versions of NSE functions in other packages.


Your problem is that aes doesn't know your function's environment and it only looks within global environment. So, the variable dat declared within the function is not visible to ggplot2's aes function unless you pass it explicitly as:

showplot1<-function(indata, inx, iny) {
    dat <- indata
    p <- ggplot(dat, aes(x=dat[,inx], y=dat[,iny]), environment = environment())
    p <- p + geom_point(size=4, alpha = 0.5)
    print(p)
}

Note the argument environment = environment() inside the ggplot() command. It should work now.

Tags:

R

Ggplot2