Local Variables Within aes
ggplot2, r
Solution
I would capture the local environment,
xy <- data.frame(x=1:10,y=1:10)
plotfunc <- function(Data, YMul = 2){
.e <- environment()
ggplot(Data, aes(x = x, y = y*YMul), environment = .e) + geom_line()
}
plotfunc(xy)
Problem
I'm trying to use a local variable in `aes` when I plot with ggplot. This is my problem boiled down to the essence: ``` xy <- data.frame(x=1:10,y=1:10) plotfunc <- function(Data,YMul=2){ ggplot(Data,aes(x=x,y=y*YMul))+geom_line() } plotfunc(xy) ``` This results in the following error: ``` Error in eval(expr, envir, enclos) : object 'YMul' not found ``` It seems as if I cannot use local variables (or function arguments) in `aes`. Could it be that it occurrs due to the content of `aes` being executed later when the local variable is out of scope? How can I avoid this problem (other than not using the local variable within `aes`)?