Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a spatial polygon into two polygons with a line

Tags:

r

terra

r-sf

r-sp

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)
like image 646
aczich Avatar asked Feb 12 '26 13:02

aczich


1 Answers

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"))
like image 68
Robert Hijmans Avatar answered Feb 17 '26 15:02

Robert Hijmans