st_make_grid
在我的学习区域(农业领域)创建20x20m的网格:
library(sf)
library(ggplot2)
# file below can be downloaded from:
# https://mega.nz/file/5TYDyToS#aIOyeeLGbH6WeSMm8YxF5rBFmrKbrb0BVd7lyYf3HOw
d <- st_read("~/Downloads/yld.sqlite")
plot(d)
网格不与场轮廓对齐。我如何旋转它,以使两者对齐?网格是从田地的边界框创建的。如何在字段中创建
sf
center <- st_centroid(st_union(d))
theta <- 4.7 * pi / 180
rotation_matrix <- matrix(c(cos(theta), sin(theta),
-sin(theta), cos(theta)), nrow = 2)
reverse_matrix <- matrix(c(cos(-theta), sin(-theta),
-sin(-theta), cos(-theta)), nrow = 2)
e <- d
st_geometry(e) <- (st_geometry(e) - center) * rotation_matrix + center
g <- st_as_sf(st_make_grid(e, cellsize = 20))
center <- st_centroid(st_union(g))
st_geometry(g) <- (st_geometry(g) - center) * reverse_matrix + center
st_crs(g) <- st_crs(d)
现在,如果我们在原始字段上绘制此网格,我们可以看到它正确对齐。
ggplot() +
geom_sf(data = d["gyld"], aes(color = gyld)) +
geom_sf(data = g, fill = NA, color = "black") +
coord_sf() +
scale_color_viridis_c(option = "A")