r sf包多边形内的质心

2023-11-27

我需要向多边形添加标签,并且通常使用质心,但是质心不会落在多边形内。我发现这个问题计算 SpatialPolygon 内/内部的质心但我正在使用 sf 包。

下面是玩具数据

rm(list = ls(all = TRUE)) #start with empty workspace

library(sf)
library(tidyverse)
library(ggrepel)

pol <- st_polygon(list(rbind(c(144, 655),c(115, 666)
                         ,c(97, 660),c(86, 640)
                         ,c(83, 610),c(97, 583)
                         ,c(154, 578),c(140, 560)
                         ,c(72, 566),c(59, 600)
                         ,c(65, 634),c(86, 678)
                         ,c(145, 678),c(144, 655)))) %>%
  st_sfc()

a = data.frame(NAME = "A")
st_geometry(a) = pol

a <- a  %>% 
  mutate(lon = map_dbl(geometry, ~st_centroid(.x)[[1]]),
     lat = map_dbl(geometry, ~st_centroid(.x)[[2]]))

ggplot() +
  geom_sf(data = a, fill = "orange") +
  geom_label_repel(data = a, aes(x = lon, y = lat, label = NAME)) 

结果如下

enter image description here


简单的答案是替换st_centroid with st_point_on_surface。如果质心位于多边形内部,则不会返回真正的质心。

a2 <- a  %>% 
  mutate(lon = map_dbl(geometry, ~st_point_on_surface(.x)[[1]]),
         lat = map_dbl(geometry, ~st_point_on_surface(.x)[[2]]))

ggplot() +
  ggplot2::geom_sf(data = a2, fill = "orange") +
  geom_label_repel(data = a2, aes(x = lon, y = lat, label = NAME))

或者

如果多边形的质心位于多边形内部,则使用该质心,否则,在多边形内找到一个点。

st_centroid_within_poly <- function (poly) {

  # check if centroid is in polygon
  centroid <- poly %>% st_centroid() 
  in_poly <- st_within(centroid, poly, sparse = F)[[1]] 

  # if it is, return that centroid
  if (in_poly) return(centroid) 

  # if not, calculate a point on the surface and return that
  centroid_in_poly <- st_point_on_surface(poly) 
  return(centroid_in_poly)
}

a3 <- a  %>% 
  mutate(lon = map_dbl(geometry, ~st_centroid_within_poly(.x)[[1]]),
         lat = map_dbl(geometry, ~st_centroid_within_poly(.x)[[2]]))

ggplot() +
  ggplot2::geom_sf(data = a3, fill = "orange") +
  geom_label_repel(data = a3, aes(x = lon, y = lat, label = NAME)) 

上面的函数st_centroid_within_polygon改编自你参考的问题为了sf包裹。更彻底地审查如何st_point_on_surface作品可以是在这里找到.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

r sf包多边形内的质心 的相关文章

随机推荐