用一条线将一个空间多边形分割成两个多边形

问题描述 投票:0回答:1

我想用一条线将一个多边形分割成多个多边形,或者在原始多边形中创建两个单独的命名区域(如果可能的话)。最终目标是让点落入两个区域之一,然后绘制多边形,其中填充 = 该区域中的点数。

我已经尝试使用 sf 和 terra 一段时间了。任何这样做的方法将不胜感激。

library(sf)

# create a polygon and a line
poly <- st_polygon(list(rbind(c(0, 0), c(1, 0), c(1, 1), c(0, 1), c(0, 0))))
line <- st_linestring(rbind(c(0.5, -0.5), c(0.5, 1.5)))

# plot the polygon and line
plot(poly)
plot(line, add = TRUE)


# split the polygon into two using the adjusted line
poly_split <- st_intersection(poly, line)

# plot the two resulting polygons
plot(poly_split)
r sf sp terra
1个回答
0
投票

对于这个简单的案例,你可以这样做

library(terra)

splitp <- function(pol, lin) {
    x <- rbind(as.lines(pol), lin)
    a <- aggregate(x)
    m <- makeNodes(a)
    as.polygons(m)
}

library(terra)
poly <- vect(rbind(c(0, 0), c(1, 0), c(1, 1), c(0, 1), c(0, 0)), "poly")
line <- vect(rbind(c(0.5, -0.5), c(0.5, 1.5)), "line")
p <- splitp(poly, line)
plot(p, col=c("blue", "red"))

有了terra 1.7-23(目前是开发版)你可以使用

split

library(terra)
# terra 1.7.23
poly <- vect(rbind(c(0, 0), c(1, 0), c(1, 1), c(0, 1), c(0, 0)), "poly")
line <- vect(rbind(c(0.5, -0.5), c(0.5, 1.5)), "line")

p <- split(poly, line)
plot(p, col=c("blue", "red"))
© www.soinside.com 2019 - 2024. All rights reserved.