I want to produce a number of .png files in a loop in R. I wrote the code and checked that the ggplot commands created and saved the .png file when I ran it for just one image.
When I executed the loop however, none of the pngs saved? Why is this happening? Does it need time to 'draw'?
Reproducible example below:
library(ggplot2)
library(tidyr)
library(ggthemes)
#set your own directory here
setwd("~/TEST")
vap=array(1:100, c(1,451,351))
#create the list
Variable <- list(Data = vap)
xyCoords <- list(x = seq(from = -10.763300, to = -5.238170, by = 0.01578607), y = seq(from = 51.36150, to = 55.43160, by = 0.009044647))
Dates <- list(start = seq(as.Date("2005-01-01"), as.Date("2005-01-02"), by="days"), end=seq(as.Date("2005-01-01"), as.Date("2005-01-02"), by="days"))
#All <- list(Variable = Variable, xyCoords=xyCoords,Dates=Dates)
All <- list(Variable = Variable,Data=vap, xyCoords=xyCoords,Dates=Dates)
timeslices <- c("2000","3000","4000")
filetime <- c("2000","3000","4000")
variable <- c("tm","nn","xx")
ress <- c("726","745","785")
season <- c("spr","sum","aut","win","ann")
xyz <- cbind(x=rep(All$xyCoords$x, length(All$xyCoords$y)), rep(All$xyCoords$y, each=length(All$xyCoords$x)),All$Data)
mydf <- as.data.frame(xyz)
colnames(mydf) <- c("mm", "x", "y")
#Navigate to the relevant directory
for (v in 1:length(variable)){
for (f in 1:length(filetime)){
#Set the file name
for (r in 1:length(ress)){
for (s in 1:length(season)){
sea<-season[s]
png_name<-sprintf("%s_%s_%s_%s_testfile.png",sea,variable[v],ress[r],timeslices[f])
mycol<-c("#8C510A","#D8B365","#F6E8C3","#F5F5F5","#C7EAE5","#5AB4AC","#01665E")
rng = range(c((0), (14))) #a range to have the same min and max for both plots
png(file=(png_name)
, width = 9, height = 9, units = 'in', res = 300, bg = "transparent")
ggplot(mydf) +
geom_tile(aes(x=x, y=y, fill=mm), alpha=0.8) +
scale_fill_gradientn(colours=mycol,space = "Lab",na.value = "transparent",guide = "colourbar",aesthetics = "fill",limits=c(floor(rng[1]), ceiling(rng[2]))) +
coord_quickmap() +
theme_map() +
theme(legend.position="right",legend.direction = "vertical",legend.key.width=unit(0.6,"cm"), legend.key.height=unit(4,"cm"))+
theme(legend.key = element_rect(fill = NA))
dev.off()
}}}}
I tried using ggsave
instead, but it made all my gridded date look like each pixel had an outline (which my method above does not).
I tried also using a 'pause' (Sys.sleep(10)
) after each png is saved, but that made no difference.