英文:
Split a spatial polygon into two polygons with a line
问题
我想要取一条线,并将其用于将一个多边形分割成多个多边形,或者在原始多边形中创建两个单独的命名区域(如果可能的话)。最终目标是使落入两个区域之一的点,然后绘制填充为该区域中的点数的多边形。
我已经尝试了一段时间使用sf和terra。欢迎任何方法来完成这个任务。
library(sf)
# 创建一个多边形和一条线
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(poly)
plot(line, add = TRUE)
# 使用调整后的线将多边形分割成两部分
poly_split <- st_intersection(poly, line)
# 绘制两个结果多边形
plot(poly_split)
英文:
I want to take a line and use it to split a polygon into multiple polygons, or to create two separate named region in the original polygon (if that's possible). The end goal would be having points that fall into one of the two regions and then plot the polygons where fill = number of points in the region.
I have tried using sf for a while and also terra. Any method of doing this would be appreciated.
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)
答案1
得分: 1
对于这个简单的案例,你可以这样做:
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"))
请注意,我已经保留了代码部分的内容不进行翻译,只提供了翻译好的文字部分。
英文:
For this simple case, you could do
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"))
With terra 1.7-23 (currently the development version) you can use 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"))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论