使用geom_sf()时无独立x、y列,如何为地图数据点添加标签?
基于sf对象geometry列添加地图点标签的解决方案
你不需要拆分geometry列,有两种直接的方法解决这个问题:
方法1:使用geom_sf_text()(推荐)
ggplot2提供了专门适配sf对象的文本图层geom_sf_text(),它会自动读取geometry列的坐标,无需手动指定x和y参数:
stc_plot <- ggplot() + geom_sf(data = stc_land, color = "grey40", fill = "grey80") + geom_sf(data = stcdens, aes(size = Density)) + # 替换geom_text为geom_sf_text,可添加nudge参数调整标签位置避免遮挡 geom_sf_text(data = stcdens, aes(label = Name), nudge_x = 0.01, nudge_y = 0.01) + labs(size = "Nesting Activities per Year") + scale_size_discrete(labels = c("<25", "25-100", "100-500")) + theme_classic() + theme(legend.position = "bottom")
nudge_x和nudge_y参数可以微调标签的偏移量,避免标签与地图点重叠,你可以根据实际地图的缩放比例调整数值。
方法2:从geometry列提取经纬度给geom_text()
如果一定要使用geom_text(),可以用sf包的st_coordinates()函数从geometry列中提取经度和纬度,生成单独的列供geom_text()使用:
# 加载dplyr(如果未加载) library(dplyr) # 提取经纬度到新列 stcdens <- stcdens %>% mutate( lon = st_coordinates(geometry)[, 1], # 提取经度 lat = st_coordinates(geometry)[, 2] # 提取纬度 ) # 使用geom_text并指定x和y参数 stc_plot <- ggplot() + geom_sf(data = stc_land, color = "grey40", fill = "grey80") + geom_sf(data = stcdens, aes(size = Density)) + geom_text(data = stcdens, aes(x = lon, y = lat, label = Name)) + labs(size = "Nesting Activities per Year") + scale_size_discrete(labels = c("<25", "25-100", "100-500")) + theme_classic() + theme(legend.position = "bottom")
两种方法都可以解决你的问题,推荐第一种,因为它更贴合sf对象的使用逻辑,不需要额外修改数据结构。
内容的提问来源于stack exchange,提问作者Makayla Kelso
相关产品推荐
相关产品推荐

