Search code examples
rfor-loopplotggplot2cowplot

Using a for loop to save multiple ggplot as jpeg


I'd like to save multiple ggplots as jpegs through a for loop. But when I've tried to adapt code I've written for a basic plot command, I get no output (nothing is saved to my working directory).

For Example, this works great:

library(cowplot)
library(ggplot)

X<-c(1,2,3,4,5,6,7,8,9)
Y1<-c(2,3,4,4,3,2,4,5,6)
Y2<-c(3,4,5,3,2,1,1,2,3)
Y3<-c(4,5,6,7,8,9,8,7,6)

DF<-data.frame(X,Y1,Y2,Y3)



for(i in 1:3){


    jpeg(paste(i,".jpeg",sep=""))
    plot(DF[,1],DF[,i+1])
    dev.off()
}

I end up getting three jpeg files saved to my working directory.

I'm not sure how to properly index the ggplot call here for i, but even this should return 3 instances of the same plot:

for(i in 1:3){


    jpeg(paste(i,".jpeg",sep=""))
    ggplot(data=DF,aes(x=X,y=Y1))+geom_line()
    dev.off()
}

In the end, I was hoping to combine multiple plots onto one jpeg, and then save multiple jpegs like this:

for(i in 1:3){


    jpeg(paste(i,".jpeg",sep=""))
    A<-ggplot(data=DF,aes(x=X,y=Y1))+geom_line()
    B<-ggplot(data=DF,aes(x=X,y=Y2))+geom_line()
    C<-ggplot(data=DF,aes(x=X,y=Y3))+geom_line()
    plot_grid(A,B,C)

    dev.off()
}

So this plot should also return 3 instances of the same plot, all with different indexed file names. But again, I get nothing.

So my question is why is there a difference between generic plotting and ggploting in this for loop. And how can one save mutliple jpegs from ggplots like above?


Solution

  • How about

    library(gridExtra) # gridExtra::arrangeGrob
    
    for(i in 1:3) {
    
        jpeg(paste0(i, ".jpg"))
        A <- ggplot(data = DF, aes(x = X, y = Y1)) + geom_line()
        B <- ggplot(data = DF, aes(x = X, y = Y2)) + geom_line()
        C <- ggplot(data = DF, aes(x = X, y = Y3)) + geom_line()
        grid.arrange(arrangeGrob(A, B, C, ncol = 3))
        dev.off()
    
    }
    

    Note: this solution does not produce the side annotations of cowplot ("A", "B", "C").