如何在 R 中为栅格中的特定数字赋予不同的颜色(或形状)?

How give certain number in a raster a different colour (or shape) in R?

我有一个光栅,其中几个像素具有此值 9999。在绘制整个光栅之前,我想为这些像素赋予特定的颜色。所以图例没有考虑这个值

  Library(raster)
  filename <- system.file("external/test.grd", package="raster")
  r <- raster(filename)
  plot(r) ### normal plot which takes into account all pixels

  r[r>1000]=9999 

   plot(r)

此处的图例(绘图)不应考虑 9999,而是给该值指定颜色(或形状)并正常绘制 r9999的传说也可以分开

您可以创建不含 9999 像元的栅格副本和仅包含 9999 像元的栅格副本并叠加它们:

library(raster)
filename <- system.file("external/test.grd", package="raster")
r <- raster(filename)
r[r>1000]=9999 

# raster without 9999
r2 = reclassify(r, matrix(c(1000, Inf, NA), ncol=3))
plot(r2, colNA = NA)

# raster with only 9999
r3 = reclassify(r, matrix(c(-Inf, 1000, NA, 1000, Inf, 9999), ncol=3, byrow=T))
plot(r3, add=T, col='black', colNA = NA, legend=F)