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

如何使用R语言tmap包将指北针定位在比例尺中心?

问题:将指北针定位在比例尺中心位置

我希望将指北针定位在比例尺的中心位置,目前使用的代码如下:

library(tmap)
library(terra)
library(sf)

r <- rast(system.file("ex/elev.tif", package="terra"))

states <- st_read(system.file("ex/lux.shp", package="terra"))

# 调整地图边界
bbox_new <- st_bbox(r) # 当前边界范围

xrange <- bbox_new$xmax - bbox_new$xmin # x轴范围
yrange <- bbox_new$ymax - bbox_new$ymin # y轴范围
bbox_new[1] <- bbox_new[1] - (0.05 * xrange) # 左边界扩展
bbox_new[3] <- bbox_new[3] + (0.05 * xrange) # 右边界扩展
bbox_new[2] <- bbox_new[2] - (0.05 * yrange) # 下边界扩展
bbox_new[4] <- bbox_new[4] + (0.05 * yrange) # 上边界扩展
bbox_new <- bbox_new %>%  # 将边界转换为sf多边形
  st_as_sfc()

tm_shape(r, bbox = bbox_new) +
  tm_raster(col.scale = tm_scale_continuous(
    values = "viridis"),  # 配色方案
    col.legend = tm_legend(title = "Legend", frame.lwd = 0,
                           position = c("LEFT", "BOTTOM"))) +
  tm_shape(states) +
  tm_borders() +
  tm_compass(position = c("RIGHT", "TOP"), size = 1, text.size = 1) +
  tm_scalebar(text.size = 1,
    breaks = c(0, 8, 16), 
    position = c("RIGHT", "TOP"))

当前效果:指北针位于比例尺的最左侧,未与比例尺中心对齐。
期望效果:指北针居中对齐在比例尺的正上方(中心位置)。


解决方案

要实现指北针在比例尺中心的效果,可通过以下两种方法调整元素位置:

方法1:用offset参数微调指北针位置

修改tm_compass代码,添加offset参数向左偏移,让指北针对齐比例尺中心,数值可根据实际显示效果微调:

tm_shape(r, bbox = bbox_new) +
  tm_raster(col.scale = tm_scale_continuous(
    values = "viridis"),  # 配色方案
    col.legend = tm_legend(title = "Legend", frame.lwd = 0,
                           position = c("LEFT", "BOTTOM"))) +
  tm_shape(states) +
  tm_borders() +
  # offset参数调整水平偏移,负数为向左偏移
  tm_compass(position = c("RIGHT", "TOP"), size = 1, text.size = 1, offset = c(-0.04, 0)) +
  tm_scalebar(text.size = 1,
    breaks = c(0, 8, 16), 
    position = c("RIGHT", "TOP"))

方法2:用数值形式position精准定位

将position设置为0-1之间的数值(代表相对画布的比例,0对应最左/最下,1对应最右/最上),分别指定指北针和比例尺的位置,确保指北针在比例尺中心正上方:

tm_shape(r, bbox = bbox_new) +
  tm_raster(col.scale = tm_scale_continuous(
    values = "viridis"),  # 配色方案
    col.legend = tm_legend(title = "Legend", frame.lwd = 0,
                           position = c("LEFT", "BOTTOM"))) +
  tm_shape(states) +
  tm_borders() +
  # 指北针位置:x=0.9(距右侧10%),y=0.95(距顶部5%)
  tm_compass(position = c(0.9, 0.95), size = 1, text.size = 1) +
  # 比例尺位置:x=0.9,y=0.92(位于指北针正下方)
  tm_scalebar(text.size = 1,
    breaks = c(0, 8, 16), 
    position = c(0.9, 0.92))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 05:38:23