exAres
exAres

Reputation: 4926

Unable to plot multiple plots in a loop?

My code for multiple plots is as

    for (i in 3:5) {
        #paste(names(normalized_ge_data))
        file_name = paste(as.character(i), ".png")
        png(file_name)
        g + geom_boxplot(aes(fill=factor(ge_data$hasServiced))) + geom_jitter()
        dev.off()
    }

I want to have files like 3.png, 4.png, and so on. How to achieve this?

Upvotes: 2

Views: 193

Answers (4)

Matt74
Matt74

Reputation: 729

If the OP is looking to strictly print the plots, the best method is probably to store the plots in a list during the loop, and then print each item in the list. Here's a suggestion:

library(ggplot2)

plot_list <- list()

for (ii in 1:5){
  temp_df <- data.frame(x=rnorm(n=15, mean=0, sd=5),
                        y=rnorm(n=15, mean=0, sd=5),
                        z=rnorm(n=15, mean=0, sd=5))
  temp_plot <- ggplot(temp_df, aes(x=x, y=y, color=z))+
    geom_point()+
    theme_bw()+
    ggtitle(paste("Group", ii))
  plot_list[[ii]] <- temp_plot
}

lapply(plot_list, print)

Of course, you could alter the lapply call to use ggsave or whatever function you'd like to use to save the plots.

Upvotes: 2

Shorpy
Shorpy

Reputation: 1579

I think for ggplot the best way to do this is with the ggsave() function:

for (i in 3:5) {
      qplot(mtcars[, i])
      ggsave(file = paste0("plot_", i, ".png"))
    }

Documentation here: http://docs.ggplot2.org/0.9.2.1/ggsave.html

Upvotes: 2

Daniel
Daniel

Reputation: 7832

I tried your example with some sample data, and it works for me:

library(sjmisc)
library(ggplot2)
data(efc)

for (i in 3:5) {
  file_name = paste0(as.character(i), ".png")
  png(file_name)
  plot(ggplot(efc, aes(x = 1, y = e17age)) + geom_boxplot() + geom_jitter())
  dev.off()
}

w/o the plot, only white, empty png's are created.

Upvotes: 1

shekeine
shekeine

Reputation: 1465

Following @Daniel 's suggestion above, this works:

g <- ggplot(mtcars, aes(factor(cyl), mpg))

for (i in 3:5) {
#paste(names(normalized_ge_data))
file_name = paste(as.character(i), ".png")
png(file_name)
print(g + geom_boxplot(aes(fill=factor(cyl))) + geom_jitter())
dev.off()
}

Upvotes: 1

Related Questions