下面的代码可以很好地映射具有物种数据的栅格文件(25 m 空间分辨率)。
问题:我正在努力区分地图外的值(背景,也视为 0)和地图内的真实 0 值。
# Load required libraries
library(terra) # for handling raster files
# Load the raster file
raster_data <- rast("pollinator.tif")
# Define categories and breaks
breaks <- seq(0, 0.03, length.out = 6) # 5 categories, so 6 breaks
categorized_raster <- classify(raster_data, rcl = cbind(breaks[-length(breaks)],
breaks[-1], 1:5))
# Handle background (outside map) values separately
background_value <- -1 # Assign a distinct value for the background
categorized_raster[is.na(values(categorized_raster))] <- background_value
# Define custom colors
colors <- c("white", "#fde725", "#5ec962", "#21918c", "#3b528b", "#440154") # Add
white for background
# Adjust the color assignment to include the background
# "white" (background) is mapped to -1, followed by the defined category colors
plot(categorized_raster, col = colors, main = "Pollinator Abundance (Andrena
strohmella, Spring)",
xlab = "Longitude", ylab = "Latitude", axes = TRUE, legend = TRUE)
示例数据
library(terra)
r <- rast(system.file("ex/elev.tif", package="terra"))
x <- classify(r, 5) |> as.int()
显而易见的解决方案是不要使用“白色”作为数据的颜色
colors <- c("#fde725", "#5ec962", "#21918c", "#3b528b", "#440154")
plot(x, col=colors)
但是如果这样做,您可以将背景 (
NA
) 颜色设置为其他颜色,在本例中为“浅灰色”。
colors <- c("white", "#fde725", "#5ec962", "#21918c", "#3b528b", "#440154")
plot(x, col=colors, colNA="light gray")