【发布时间】:2019-03-02 12:50:55
【问题描述】:
我需要为多边形添加标签,我通常使用质心,但是质心不会落在多边形内。我发现了这个问题Calculate Centroid WITHIN / INSIDE a 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))
结果如下
【问题讨论】:
-
您可以将
~st_centroid替换为~st_point_on_surface。也就是说,如果您不关心在任何多边形上拥有真正的质心。 -
这个问题有更多关于
st_PointOnSurfacefrom postgis gis.stackexchange.com/questions/76498/…的信息