我有四个光栅和一个形状文件。我想在单个面板中的 4 个栅格之上绘制 shapefile
library(terra)
r1 <- r2 <- r3 <- r4 <- rast(ncol=10, nrow=10, xmin=-150, xmax=-80, ymin=20, ymax=60)
values(r1) <- runif(ncell(r1))
values(r2) <- runif(ncell(r2))
values(r3) <- runif(ncell(r3))
values(r4) <- runif(ncell(r4))
rr <- c(r1, r2, r3, r4)
# shapefile
lon <- c(-116.8, -114.2, -112.9, -111.9, -114.2, -115.4, -117.7)
lat <- c(41.3, 42.9, 42.4, 39.8, 37.6, 38.3, 37.6)
lonlat <- cbind(lon, lat)
pols <- vect(lonlat, type="polygons", crs="epsg:4326")
terra::plot(rr)
terra::plot(pols, add = T)
但是,shapefile 并未添加到栅格中,而是绘制在中间。
您的示例数据
library(terra)
r <- rast(ncol=10, nrow=10, nlyr=4, xmin=-150, xmax=-80, ymin=20, ymax=60)
values(r) <- 1:size(r)
# polygons
lon <- c(-116.8, -114.2, -112.9, -111.9, -114.2, -115.4, -117.7)
lat <- c(41.3, 42.9, 42.4, 39.8, 37.6, 38.3, 37.6)
pols <- vect(cbind(lon, lat), type="polygons", crs="+proj=longlat +datum=WGS84")
解决方案
plot(r, fun=function()lines(pols))