r sf package centroid within polygon
我需要为多边形添加标签,我通常使用质心,但是质心不会落在多边形内。我发现了这个问题 Calculate Centroid WITHIN / INSIDE a SpatialPolygon 但我使用的是 sf 包。
下面是玩具数据
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
rm(list = ls(all = TRUE)) #start with empty workspace
library(sf) pol <- st_polygon(list(rbind(c(144, 655),c(115, 666) a = data.frame(NAME =”A”) a <- a %>% ggplot() + |
导致以下
- 您可以将 ~st_centroid 替换为 ~st_point_on_surface。也就是说,如果您不关心任何多边形上的真实质心。
- 这个问题有更多关于 postgis gis.stackexchange.com/questions/76498/… st_PointOnSurface 的信息。
简单的答案是将st_centroid 替换为st_point_on_surface。如果质心位于多边形内部,这将不会返回真正的质心。
1
2 3 4 5 6 7 |
a2 <- a %>%
mutate(lon = map_dbl(geometry, ~st_point_on_surface(.x)[[1]]), lat = map_dbl(geometry, ~st_point_on_surface(.x)[[2]])) ggplot() + |
或者
如果多边形的质心在多边形内,则使用它,否则,在多边形内找到一个点。
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
st_centroid_within_poly <- function (poly) {
# check if centroid is in polygon # if it is, return that centroid # if not, calculate a point on the surface and return that a3 <- a %>% ggplot() + |
st_centroid_within_polygon 上面的函数改编自您为 sf 包引用的问题。可以在此处找到对 st_point_on_surface 工作原理的更全面的回顾。
扩展 Mitch 的答案,因为上面提供的 st_centroid_within_poly 函数仅适用于单个多边形。
要在多个多边形上使用,请使用:
1
2 3 4 5 6 7 8 9 10 11 |
st_centroid_within_poly <- function (poly) {
# check if centroid is in polygon # replace geometries that are not within polygon with st_point_on_surface() ctrd |
- 它在 st_geometry(ctrd[!in_poly,]) <- st_geometry(st_point_on_surface(poly[!in_poly,])) 与 Error in poly[!in_poly, ] : incorrect number of dimensions 失败
来源:https://www.codenong.com/52522872/