Hello there, I'm trying to do lots of plots in one for-loop. But somehow ggplot does not evaluate arguments as expected. Here is an example: library(lattice) library(ggplot2) pl <- list() pl2 <- list() cDat <- as.data.frame(cbind(x1=0:100,x2=0:10,x3=1:20)) for(obs in c("x1", "x2")) { pl[[obs]] <- xyplot(cDat[,obs] ~ cDat[,"x3"], main=obs) pl2[[obs]] <- qplot(cDat[,"x3"], cDat[,obs], main=obs) } The pl list contains finally my desired result pl$x1 and pl$x2 are different and show what I want it to. Now, the plots pl2$x1 and pl2$x2 are the same - they both show an x2 ~ x3 plot since this is the current value of obs. So how can I force the variable name substitution? I tried some combinations of parse/eval/substitute with no success. Thanks for your help in advance. Greetings, Sebastian Weber
On Wed, Mar 26, 2008 at 11:03 AM, Sebastian Weber <sebastian.weber at physik.tu-darmstadt.de> wrote:> Hello there, > > I'm trying to do lots of plots in one for-loop. But somehow ggplot does > not evaluate arguments as expected. Here is an example: > > library(lattice) > library(ggplot2) > pl <- list() > pl2 <- list() > cDat <- as.data.frame(cbind(x1=0:100,x2=0:10,x3=1:20)) > for(obs in c("x1", "x2")) { > pl[[obs]] <- xyplot(cDat[,obs] ~ cDat[,"x3"], main=obs) > pl2[[obs]] <- qplot(cDat[,"x3"], cDat[,obs], main=obs) > } > > The pl list contains finally my desired result pl$x1 and pl$x2 are > different and show what I want it to. Now, the plots pl2$x1 and pl2$x2 > are the same - they both show an x2 ~ x3 plot since this is the current > value of obs. So how can I force the variable name substitution? I tried > some combinations of parse/eval/substitute with no success.In this case you are better off moving away from qplot (which does various substitute tricks to assemble the named variables in a data frame) to a more explicit form of ggplot: pl2[[obs]] <- ggplot(cData, aes_string(x="x3", y=obs)) + geom_point() + opts(title = obs) Hadley -- http://had.co.nz/
Hi!> In this case you are better off moving away from qplot (which does > various substitute tricks to assemble the named variables in a data > frame) to a more explicit form of ggplot: > > pl2[[obs]] <- ggplot(cData, aes_string(x="x3", y=obs)) + geom_point() > + opts(title = obs)Ok, I will try that, thanks. BTW, where is this aes_string option documented, sounds useful? How could I do the same thing with facetting? If I want to save something like ". ~ groupVar" as a string in a variable, could I pass it with facet_string to ggplot? But anyway, I would be curious how to do it with qplot. The basic question is: How to pass the string of a variable to a function which is supposed to interpret it. Aka: var <- "magicVar" fun(doSomeMagic(var)) doSomeMagic should then write magicVar at the place. Greetings, Sebastian Weber> > Hadley > >