2

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?

3
  • I guess it should work if you surround your g + geom... line with plot(...). Commented May 5, 2015 at 11:53
  • like plot(g + geom_boxplot(aes(fill=factor(ge_data$hasServiced))) + geom_jitter())? Commented May 5, 2015 at 11:54
  • yes. I have no quick example at hand to verify my suggestion, but I think I have done it in this way already. print() or plot() should work. Commented May 5, 2015 at 11:55

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.