首页 > 解决方案 > 在 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'))

标签: rlabelgispolygon

解决方案


使用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 包(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')) 

在此处输入图像描述


推荐阅读