在shapefile图的顶部添加标签

问题描述

考虑一个示例数据集,其中有四个多边形:

enter image description here

我希望多边形的颜色基于其所属的组,要显示每种颜色含义的图例以及在每个多边形上带有门牌号的标签。

以下代码按组区分颜色:

plot(df$geometry,col=df$group) 

enter image description here

上面示例中的可复制数据:

structure(list(shape = c("polygon 1","polygon 2","polygon 3","polygon 4"),geometry = structure(list(structure(list(structure(c(0,1,1),.Dim = c(5L,2L))),class = c("XY","POLYGON","sfg"),precision = 0,bbox = structure(c(xmin = 0,ymin = 0,xmax = 1,ymax = 1),class = "bbox"),crs = structure(list(
input = NA_character_,wkt = NA_character_),class = "crs"),n_empty = 
0L),structure(list(structure(c(2,3,2,3),bbox = 
structure(c(xmin = 2,ymin = 2,xmax = 3,ymax = 3),crs = structure(list(
    input = NA_character_,n_empty = 0L),structure(list(structure(c(4,5,4,4),bbox = 
structure(c(xmin = 4,ymin = 4,xmax = 5,ymax = 5),structure(list(structure(c(6,7,6,7),bbox = 
structure(c(xmin = 6,ymin = 6,xmax = 7,ymax = 7),n_empty = 0L)),n_empty = 
0L,class = c("sfc_POLYGON","sfc")),group = c(1,2),house = c(1,4)),row.names = 
c(NA,4L),class = c("sf","tbl_df","tbl","data.frame"),sf_column = 
"geometry",agr = structure(c(shape = NA_integer_,group = NA_integer_,house = NA_integer_),class = "factor",.Label = 
c("constant","aggregate","identity")))

解决方法

我无法使用基本的plot()进行绘制。但是,我认为我使用 ggplot 包以一种更具可读性的方式实现了您的目标,如下所示:

# setup environment
library(ggplot2)
# define a data frame with x and y coordinates and their groups
df = data.frame(
  group = rep(1:2,each = 8),house = rep(1:4,each = 4),x = c(0,1,2,3,4,5,6,7,6),y = c(0,7),)
# create a data frame with text labels and their coordinates
lbl = df %>%
  group_by(house) %>%
  summarise(x = mean(x),y = max(y) + 0.5) %>%
  unique()
# plot the houses using ggplot package
ggplot(df,aes(x,y)) +
  geom_polygon(aes(fill = group,group = house),colour = 'black') +
  labs(title = 'House Geometries',x = 'X',y = 'Y') +
  scale_fill_manual(name = 'House',values = c('black','red')) +
  annotate('text',x = lbl$x,y = lbl$y,label = lbl$house,size = 6) +
  theme(plot.title = element_text(size = 19,face = 'bold',hjust = 0.5),legend.title = element_text(size = 15,legend.text = element_text(size = 14,axis.title.x = element_text(size = 15),axis.text.x = element_text(size = 14),axis.title.y = element_text(size = 15),axis.text.y = element_text(size = 14))

这是最后的情节:

enter image description here

顺便说一句,我从事土木工程,您的问题对我来说很有趣...

让我知道您是否打算这样做。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...