将多个光栅图写为 .png

问题描述

我正在 R 中读取多个 .tif 文件,并将小于 6000 的栅格值转换为 NA,然后绘制栅格并将其作为 .png 保存在文件夹中。除了输出 png 光栅图为空外,一切正常。这是我正在使用的代码 -

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()
}

我可以很容易地在单个栅格上执行此操作,但需要运行循环来处理 300 个 .tif。

解决方法

您必须 print 您的情节才能使其在 png 中可见: 假数据示例:

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()
}