Hi there

Save ggplots in a for Loop

Yonghui Dong / 2018-06-11


I have been trying to save multiple plots produced by ggplot2. It was not as easy as I expected. Below are two efficient ways that I found online.

Example 1:

library(ggplot2)
p <- ggplot(iris, aes(x = Species, y = Sepal.Length))
colors <- c("black", "red", "green")
for(color in colors){
  final.plot <- p + geom_boxplot(color = color)
  pdf(paste0(color, ".pdf"))
  print(final.plot)
  dev.off()
}

Example 2:

library(ggplot2)
p <- ggplot(iris, aes(x = Species, y = Sepal.Length))
colors <- c("black", "red", "green")
for(color in colors){
  final.plot <- p + geom_boxplot(color = color)
  ggsave(final.plot, file = paste0(color, ".pdf"), scale = 2) 
  print(final.plot)
}

Here is the trick:

To save multiple ggplots using for loop, you need to call the function print() explicitly to plot a ggplot to a device such as PDF, PNG, JPG file.