问题描述
我正在尝试向Spatialpolygons添加标签,这些标签将在多边形外部绘制。 我正在使用R和基本绘图功能来堆叠地图的图层。
这是带有来自polygonsLabel()函数的标签的多边形的示例。 (https://www.rdocumentation.org/packages/rgeos/versions/0.3-5/topics/polygonsLabel)
#Create polygons
x1 = c(0,4,0)
y1 = c(0,0)
x2 = c(1,1,3,1)
y2 = c(-2,-10,-2,-2)
x3 = c(6,14,6,6)
y3 = c(1,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'))
解决方法
使用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,0)
y1 = c(0,0)
x2 = c(1,1,3,1)
y2 = c(-2,-10,-2,-2)
x3 = c(6,14,6,6)
y3 = c(1,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','maroon')) +
geom_sf_label_repel(aes(label = labels),nudge_y = -3,nudge_x = +2,force = 100)
由reprex package(v0.3.0)于2020-10-01创建
*编辑:
从边缘标记线:
ggplot(xy_sf) +
geom_sf_label_repel(aes(label = labels),force = 100) +
geom_sf(fill = c('white','maroon'))