You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中使sf网格与多边形(农田)对齐及优化?

解决sf包st_make_grid生成农田网格的两个问题

我尝试用sf包的st_make_grid函数在一片农田研究区创建20×20m的网格,初始代码及效果如下:

library(sf)
library(ggplot2)

# 读取农田数据
d <- st_read("~/Downloads/yld.sqlite")
plot(d)

农田轮廓

# 生成初始网格
g <- st_as_sf(st_make_grid(d, cellsize = 20))

ggplot() + 
  geom_sf(data = g) +
  geom_sf(data = d["gyld"], fill = "grey", color = "grey") +
  coord_sf()

基于农田生成的网格

当前遇到两个问题:

  1. 网格与农田轮廓未对齐,如何旋转网格使其对齐?
  2. 当前网格基于农田的边界框创建,如何仅在农田内部生成网格?

1. 旋转网格使其与农田轮廓对齐

要让网格匹配农田的倾斜轮廓,需先获取农田多边形的主方向角度,再对网格做对应角度的旋转。借助lwgeom包的st_orientation函数可实现:

library(sf)
library(ggplot2)
library(lwgeom) # 需提前安装:install.packages("lwgeom")

# 读取数据
d <- st_read("~/Downloads/yld.sqlite")

# 获取农田多边形的主倾斜方向(弧度制)
orientation_rad <- st_orientation(d)

# 步骤1:将农田旋转至轴对齐状态
d_rotated <- st_rotate(d, -orientation_rad)
# 步骤2:在旋转后的农田边界框内生成网格
g_rotated <- st_as_sf(st_make_grid(d_rotated, cellsize = 20))
# 步骤3:将网格旋转回原方向,实现与农田轮廓对齐
g_aligned <- st_rotate(g_rotated, orientation_rad)

# 查看对齐效果
ggplot() + 
  geom_sf(data = g_aligned) +
  geom_sf(data = d["gyld"], fill = "grey", color = "grey") +
  coord_sf()

2. 仅在农田内部生成网格

通过空间交集操作,可裁剪掉农田范围外的网格单元,保留内部网格:

方法1:保留所有与农田相交的网格(含部分重叠)

# 对对齐后的网格与农田做空间交集
g_inside <- st_intersection(g_aligned, d)

# 绘图展示
ggplot() + 
  geom_sf(data = g_inside, fill = "lightblue", color = "darkblue") +
  geom_sf(data = d["gyld"], fill = "grey", color = "black", alpha = 0.3) +
  coord_sf()

方法2:仅保留完全位于农田内的网格

若需筛选完全在农田内部的网格,可通过判断网格中心点是否在农田内实现:

# 获取网格中心点
g_centers <- st_centroid(g_aligned)
# 筛选中心点位于农田内的网格
g_fully_inside <- g_aligned[st_within(g_centers, d, sparse = FALSE), ]

# 绘图展示
ggplot() + 
  geom_sf(data = g_fully_inside, fill = "lightgreen", color = "darkgreen") +
  geom_sf(data = d["gyld"], fill = "grey", color = "black", alpha = 0.3) +
  coord_sf()

内容的提问来源于stack exchange,提问作者thiagoveloso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 18:55:55