[R] ggplot doesnt work in loops?

hadley wickham h.wickham at gmail.com
Thu Jul 12 09:55:06 CEST 2007

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){
        p + aes(x = mydata$varc)

(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)


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.

More information about the R-help mailing list