I have been struggling with this for quite a while. I have found some similar questions here but all of them seemed like an overkill for this particular problem. I have two partially overlapping polygons that I want to subtract from each other (subtracting the sel_pol
from base_pol
). After that, the resulting polygon (diff
) is to be further split along the vertical straight-line x=20
. This is where I am stuck.
First, I used the sf
package. This helped me to subtract the two polygons from each other and retrieve the resulting diff
polygon's vertices. However, I couldn't find any functionality to split the resulting polygon at x=20
within the sf
package, so I turned to another package, the lwgeom
.
Unfortunately, however, I have two main issues here. First, the st_split
function returns the vertices in a weird format: GEOMETRYCOLLECTION (POLYGON ((5 0.55, 5 0.6, 19 0.6, 23 0.5, 20.5 0.5, 17 0.55, 5 0.55)))
, and I am unsure how to use this to pass the vertices further along my code in the same intuitive way as I could using the sf
, and, second, the resulting vertices are wrong. It didn't cut the diff
polygon.
Clearly, I am doing something wrong here. I also dislike the fact that I have to use two separate libraries for such a basic operation. If someone could give me a hint on how to make this process neater, I would be very grateful.
My reproducible example is as follows:
library(ggplot2)
library(sf)
library(lwgeom)
rm(list = ls())
group_prc <- data.frame(x = c(5, 23, 19, 5), y = c(0.5, 0.5, 0.6, 0.6), group = "prc")
group_exp <- data.frame(x = c(5, 24, 17, 5), y = c(0.45, 0.45, 0.55, 0.55), group = "exp")
base_pol<- Polygons(list(Polygon(group_prc[, c("x", "y")])), "base")
sel_pol <- Polygons(list(Polygon(group_exp[, c("x", "y")])), "sel")
shape <- SpatialPolygons(list(base_pol, sel_pol))
diff <- shape["base"]-shape["sel"]
diffVert <- diff@polygons[[1]]@Polygons[[1]]@coords
diffVert
dat <- rbind(group_prc, group_exp, data.frame(diffVert, group = "diff"))
dat
ggplot(dat, aes(x = x, y = y, fill = group)) + geom_polygon(alpha = 0.5) + geom_vline(xintercept = 20)
splitRes <- st_split(st_polygon(list(diff@polygons[[1]]@Polygons[[1]]@coords)),
st_linestring(rbind(c(20,20), c(0, 1))))
splitRes
And here is a visual representation. The purple area is what I call diff
in my code, and I would like to get the vertices (and eventually the area) of everything lying to the left from x=20
of the diff
polygon.