You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot2绘制的栅格地图上为geom_point点添加显示标签

ggplot2栅格地图添加点标签的实现方法

你可以通过补充标签图层实现需求,具体操作如下:

  1. 点分布稀疏的场景可直接使用ggplot2内置的geom_text()图层实现基础标签效果
  2. 点较为密集存在标签重叠问题时,可使用ggrepel包的geom_text_repel()自动优化标签位置

完整修改后的代码示例

library(gstat)
library(sp)
library(tidyr)
library(dplyr)
library(rgdal)
library(sf)
library(raster)
library(ggplot2)
library(viridis)
library(ggthemes)
# 使用防重叠标签的话需先安装加载ggrepel,基础实现可以跳过该步骤
# install.packages("ggrepel")
library(ggrepel)

# converting raster to df for ggplot
test_spdf <- as(raster, "SpatialPixelsDataFrame")
test_df <- as.data.frame(test_spdf)
colnames(test_df) <- c("value", "x", "y") 

# creates my points df from a spatialpointdataframe
dpts <- data.frame(estacoes@coords)
dpts$nomes <- estacoes$abrv
colnames(dpts) <- c("x", "y", "nome")

spf <- pauf # is my spatial polygons object

test <- ggplot() +  
  geom_tile(data=test_df, aes(x=x, y=y, fill=value), alpha=0.8) + 
  geom_polygon(data=spf, aes(x=long, y=lat, group=group), 
               fill=NA, size=0.25) +
  scale_fill_viridis(option="D") +
  coord_equal() +
  theme_map() +
  theme(legend.position="bottom") +
  theme(legend.key.width=unit(2, "cm")) + 
  geom_point(data=dpts, aes(x=x, y=y), size=3, shape=4) +
  # 基础标签实现,和下方防重叠实现二选一即可
  # geom_text(data = dpts, aes(x = x, y = y, label = nome),
  #           nudge_y = 0.2, # 根据你的坐标范围调整偏移量,避免标签覆盖点
  #           size = 3)
  # 防重叠标签实现,和上方基础实现二选一即可
  geom_text_repel(data = dpts, aes(x = x, y = y, label = nome),
                  size = 3,
                  max.overlaps = 50,
                  box.padding = 0.3)

参数调整说明

  • nudge_x/nudge_y:控制标签相对于点的偏移距离,可根据你的地图坐标尺度灵活调整
  • size:调整标签的字体大小,适配你的出图尺寸
  • max.overlaps:允许显示的重叠标签上限,标签较多时可调大该值

内容的提问来源于stack exchange,提问作者noob_researcher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 12:57:01