如何解决在shapefile图的顶部添加标签
考虑一个示例数据集,其中有四个多边形:
我希望多边形的颜色基于其所属的组,要显示每种颜色含义的图例以及在每个多边形上带有门牌号的标签。
以下代码按组区分颜色:
plot(df$geometry,col=df$group)
上面示例中的可复制数据:
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))
这是最后的情节:
顺便说一句,我从事土木工程,您的问题对我来说很有趣...
让我知道您是否打算这样做。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。