使用sf 和ggsflabel 包应该可以得到你想要的。
下面我已将您的sp 对象更改为sf(简单功能)对象,然后添加标签文本列。
ggsflabel 包信息可以在以下位置找到:https://yutannihilation.github.io/ggsflabel/index.html
您可能需要调整情节的轻推和力度。
library(rgeos)
#> Loading required package: sp
#> rgeos version: 0.5-3, (SVN revision 634)
#> GEOS runtime version: 3.8.0-CAPI-1.13.1
#> Linking to sp version: 1.4-2
#> Polygon checking: TRUE
library(sf)
#> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1
library(tidyverse)
library(sp)
library(ggsflabel)
#>
#> Attaching package: 'ggsflabel'
#> The following objects are masked from 'package:ggplot2':
#>
#> geom_sf_label, geom_sf_text, StatSfCoordinates
x1 = c(0, 4, 4, 0, 0)
y1 = c(0, 0, 4, 4, 0)
x2 = c(1, 1, 3, 3, 1)
y2 = c(-2, -10, -10, -2, -2)
x3 = c(6, 14, 14, 6, 6)
y3 = c(1, 1, 3, 3, 1)
xy.sp = SpatialPolygons(list(
Polygons(list(Polygon(cbind(x1,y1))), ID = "test1"), # box
Polygons(list(Polygon(cbind(x3,y3))), ID = "test3"), # wide
Polygons(list(Polygon(cbind(x2,y2))), ID = "test2") # high
))
rm(x1, y1, x2, y2, x3, y3)
#Plot polygons
plot(xy.sp, col=terrain.colors(3))
#Add labels:
labels=c("Hi!", "A very long text string", "N
a
r
r
o
w")
polygonsLabel(xy.sp, labels, cex=.8,
col = c('white', 'black', 'maroon'))
#> [,1] [,2]
#> [1,] 2.001002 1.966994
#> [2,] 9.828784 2.000169
#> [3,] 1.999282 -6.597297
# Change sp object to sf, and add a label column
xy_sf <- st_as_sf(xy.sp)
xy_sf$labels <- labels
ggplot(xy_sf) +
geom_sf(fill = c('white', 'black', 'maroon')) +
geom_sf_label_repel(aes(label = labels),
nudge_y = -3,
nudge_x = +2,
force = 100)
由reprex package (v0.3.0) 于 2020 年 10 月 1 日创建
*编辑:
标签线从边缘:
ggplot(xy_sf) +
geom_sf_label_repel(aes(label = labels),
nudge_y = -3,
nudge_x = +2,
force = 100) +
geom_sf(fill = c('white', 'black', 'maroon'))