[R] ggplot doesnt work in loops?

hadley wickham
Thu, 12 Jul 2007 07:55:06 -0000

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)

Hadley

On 7/12/07, Steve Powell <steve at promente.org>
wrote:
> Dear list members
> I am still a newbie so might be asking a stupid question, but I can't
get
> ggplot to work in a loop (or a "while" statement for that
matter).
>
> # to take a minimal example -
> mydata$varc = c(1,2,3)
> for (i in 1:1){
>         jpeg("test3.jpg")
>         plot(mydata$varc)
>         #ggplot(mydata, aes(x=mydata$varc)) + geom_bar()
>         dev.off()
> }
>
> this produces an empty jpeg, whereas the content of the loop produces the
> jpeg correctly.
> a standard plot() does work inside the loop.
> Any ideas? This is with R 2.4.0 and ggplot2
> thanks in advance
>
> Steve Powell
>
> proMENTE social research
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>