Search code examples
rfor-looppngr-raster

Write multiple raster plots as .png


I'm reading multiple .tif files in R and am converting raster value less than 6000 as NA, and then plotting the raster and saving it in folder as .png. Everything works fine except that output png raster plots are empty. Here is my code which I'm using -

library(raster)

#get the path
path <- "C:/lab/fire/photo_2/gif_images/gif_images_2"

#list all files
files <- list.files(path, pattern = "tif$", full.names = TRUE)
files
for (i in 1:length(files)){
  # load one raster
  r <- raster(files[i])
  values(r)[values(r) < 6000] = NA
  png(paste("plot_", i, ".png", sep = ""), width=600, height=500, res=120)
  plot(r)
  dev.off()
}

I can do this on single rasters quite easily but need to run the loop to account for 300 .tifs.


Solution

  • You have to print your plot to make it visible in png: An example with fake data:

    library(raster)
    
    r <- s <- t <- u <- v <- z <- raster()
    r[] <- s[] <- t[] <- u[] <- v[] <- z[] <- 1:ncell(r)
    rast.list <- list(r,s,t,u,v,z)
    
    for (i in 1:length(rast.list)){
     r <- rast.list[[i]]
     r <- clamp(r, -Inf, 6000)
     png(paste("plot_", i, ".png", sep = ""), width=600, height=500, res=120)
     print(plot(r))
     dev.off()
    }