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

tmap静态地图中是否有类似ggrepel::geom_text_repel的点/文本排斥功能?

tmap静态模式实现点与文本排斥(类似ggrepel)

tmap的静态plot模式没有内置类似ggrepel::geom_text_repel的点文本排斥功能,但可以借助ggrepel包计算偏移后的坐标,再在tmap中实现需求。以下是针对你提供的数据集的解决方案:

步骤与代码

1. 加载所需包

library(spData)
library(tmap)
library(dplyr)
library(sf)
library(ggrepel)

2. 处理数据并计算排斥后的坐标

# 提取目标子集
cycle_hire_sub <- cycle_hire %>% 
  arrange(desc(geometry)) %>% 
  slice(20:50)

# 提取原始坐标并转成非空间数据框用于ggrepel计算
cycle_hire_coords <- cycle_hire_sub %>% 
  mutate(
    x = st_coordinates(geometry)[,1],
    y = st_coordinates(geometry)[,2]
  ) %>% 
  st_drop_geometry()

# 用ggrepel计算排斥后的文本位置
repel_positions <- ggrepel::position_repel(
  data = cycle_hire_coords,
  x = x, y = y,
  label = id,
  point.size = 3, # 匹配tm_dots的size参数
  seed = 123 # 固定种子确保结果可复现
)

# 将排斥坐标合并回空间数据
cycle_hire_sub <- cycle_hire_sub %>% 
  mutate(
    x_repel = repel_positions$x,
    y_repel = repel_positions$y
  )

# 创建连线的空间数据框
lines_sf <- cycle_hire_sub %>% 
  rowwise() %>% 
  mutate(
    line_geom = st_linestring(
      matrix(c(st_coordinates(geometry)[1], st_coordinates(geometry)[2], x_repel, y_repel), 
             ncol = 2, byrow = TRUE)
    ) %>% st_sfc(crs = st_crs(.))
  ) %>% 
  ungroup() %>% 
  select(line_geom) %>% 
  st_set_geometry("line_geom")

3. 绘制静态地图

tmap_mode("plot")

tm_shape(cycle_hire_sub) +
  tm_dots(size = 3, col = "navy") + # 原始点
  tm_shape(lines_sf) +
  tm_lines(col = "gray50", lwd = 0.5) + # 原始点到文本的连线
  tm_text(
    text = "id", col = "white",
    x = "x_repel", y = "y_repel" # 使用排斥后的坐标绘制文本
  )

说明

  • 核心逻辑是利用ggrepel的位置计算能力,得到文本排斥后的坐标,再在tmap中分别绘制原始点、连线和偏移文本。
  • 通过seed参数固定随机种子,确保每次运行的排斥结果一致。
  • 连线的颜色和粗细可根据需求调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 01:42:46