[R] ggplot doesnt work in loops?

hadley wickham h.wickham at gmail.com
Thu Jul 12 16:36:28 CEST 2007


On 7/12/07, hadley wickham <h.wickham at gmail.com> wrote:
> Hi Steve,
>
> You need to explicitly print the ggplot object:
> ggplot(mydata, aes(x=mydata$varc)) + geom_bar()
>
> (this is a R-faq for lattice plots, and ggplot works the same way)
>
> In the latest version of ggplot (0.5.4) you can construct the plot
> before hand and modify the aesthetics in each instance of the loop:
>
> p <- ggplot(mydata) + geom_bar()
> mydata$varc = c(1,2,3)
> for (i in 1:1){
>         jpeg("test3.jpg")
>         p + aes(x = mydata$varc)
>         dev.off()
> }
>
> (not that this will actually work because you're not using i inside
> your loop anywhere)
>
> (and to be strictly correct you should probably use list(x =
> as.name(names(mydata)[i]))  instead of the aes call - but I haven't
> written any documentation for this yet)

Actually a better solution (will be included in the next version of ggplot) is:

aes_string <- function(...) structure(lapply(list(...), as.name),
class="uneval")

p + aes_string(x = names(mydata)[i])

It converts aes(x = "x", y="y") to aes(x=x, y=y).  The first is easy
to generate programmatically, the second is less to type.

Hadley



More information about the R-help mailing list