在 SpatialPolygons (R) 之外绘制标签

Plot labels outside SpatialPolygons (R)

我正在尝试向将绘制在多边形外部的 SpatialPolygons 添加标签。 我正在使用 R 和基本绘图函数来堆叠地图的图层。

这是一个带有来自 polygonsLabel() 函数的标签的多边形示例。 (https://www.rdocumentation.org/packages/rgeos/versions/0.3-5/topics/polygonsLabel)

#Create polygons 
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
))

#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'))

使用 sfggsflabel 包应该可以满足您的需求。

下面我已将您的 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'))