Consider this use of ggplot(...)
inside a function.
x <- seq(1,10,by=0.1)
df <- data.frame(x,y1=x, y2=cos(2*x)/(1+x))
library(ggplot2)
gg.fun <- function(){
i=2
plot(ggplot(df,aes(x=x,y=df[,i]))+geom_line())
}
if(exists("i")) remove(i)
gg.fun()
# Error in `[.data.frame`(df, , i) : object 'i' not found
i=3
gg.fun() # plots df[,3] vs. x
It looks like ggplot
does not recognize the variable i
defined inside the function, but does recognize i
if it is defined in the global environment. Why is that?
Note that this gives the expected result.
gg.new <- function(){
i=2
plot(ggplot(data.frame(x=df$x,y=df[,i]),aes(x,y)) + geom_line())
}
if(exists("i")) remove(i)
gg.new() # plots df[,2] vs. x
i=3
gg.new() # also plots df[,2] vs. x
Let's return a non-rendered
ggplot
object to see what's going on:As we can see,
mapping
fory
is simply an unevaluated expression. Now, when we ask to do the actual plotting, the expression is evaluated withinplot_env
, which is global. I do not know why it is done so; I believe there are reasons for that.Here's a demo that can override this behaviour: