0

I have a list of ggplots created using dlply using the data below:

d <- data.frame(
  id1 = rep(letters[1:4],16),
  id2 = c(rep("one",16), rep("two",16), rep("three",16), rep("four",16)),
  x = rnorm(64, mean=12, sd=6),
  y = rnorm(64, mean=4.5, sd=2))

require(dplyr)
require(plyr)
require(ggplot2)

d.m <- melt(d, id=c("id1","id2"))

 p = ggplot(data = d, aes(x=x, y=y))+
     geom_point()

plots = dlply(d, .(id1, id2), 
 function(x) p %+% x + ggtitle(paste(unique(x$id1), unique(x$id2)))))

This creates ggplots with custom titles based on the factor combinations id1 and id2. Now, how do I plot each of these to its own file, with similar partitioning of the filename based on the factors?

I tried a for loop and ggsave:

setwd("C:/")
for (i in (1:length(plots))){
  plots[[i]]
  ggsave(paste(names(plots[[i]]),".jpg",sep=""), dpi=600)
  }

While I see it cycling through image saves in the console ("Saving 7.04 x 5.78 in image" repeated over and over), only one file gets saved in my windows explorer, and it contains the ggplot of the last indexed plot only. Any hints as to how to plot each ggplot in a "list" with some naming control?

AndMan21
  • 533
  • 1
  • 4
  • 15
  • 2
    The reason that only one file gets saved is because the plot argument to ggsave defaults to the last plot displayed. This [Saving multiple ggplots from ls into one and seperate files in R](http://stackoverflow.com/questions/20500706/saving-multiple-ggplots-from-ls-into-one-and-seperate-files-in-r) might help you – Imran Ali Jan 23 '16 at 03:07
  • 3
    `ggsave(paste0(names(plots[[i]]),".png"), plots[[i]])` should help – baptiste Jan 23 '16 at 03:36

0 Answers0