2

today while trying to make a R script to plot several maps in a folder, I came to a situation that I can't understand and/or fix. I wrote the following code, that would be the script to plot 1 map per each 2 weeks during 31 periods (62 weeks), the script works fine if I run it alone (without the loop) but as soon I place the loop, there will be no files created and the script ends inmediately (and all the variables are changed as if it had run).

Note that raw is a dataset (as I said the code works if the loop is not there, for only 1 iteration), the al1 is the map definition that is defined as well.

date_actual <- as.Date("2012-01-01") 
i <- 0
for(i in 1:31){
  conc <- subset(raw,(raw$Day >= date_actual & raw$Day < (14+date_actual))) 
  png(filename=paste("map_",date_actual,".png",sep=""), width = 1920, height = 1080, units = "px")
  ggmap(al1) + geom_point(data = conc, aes(x = Lon, y = Lat, size = Mag), colour="red", alpha = .5) + scale_size_area(max_size=8, name="Magnitude",breaks=c(1,3,5,7,9)) + ggtitle(paste("",format(date_actual, "%Y-%U"),sep="")) + theme(plot.title = element_text(lineheight=1.2, face="bold"))
  date_actual <- date_actual + 14
  dev.off()
}
heythatsmekri
  • 781
  • 2
  • 8
  • 16

1 Answers1

3

This is FAQ 7.22 (but is less obvious with ggplot2 graphs, since they are not mentioned in the question, only the answer).

Basically ggplot2 graphs (and lattice graphs, and some others) don't actually plot until they are printed. Outside of the loop the autoprinting in R did this for you, but autoprinting does not happen inside of loops, so R never was told to actually create the plots.

The solution is to wrap the line that creates the graph in print() or plot().

Greg Snow
  • 48,497
  • 6
  • 83
  • 110
  • Thanks, that worked, I tried with another plotting systems (different from ggplot2) and they worked fine without the need of the print() function call. This was I was doing bad in this case, really thanks and I will take note of this. Cheers – heythatsmekri May 02 '15 at 16:44