如何在tmap的tm_facets中仅添加一次指北针和比例尺?
在tmap分面图中仅显示一次指北针和比例尺
要解决分面图中每个面板都重复显示指北针与比例尺的问题,可通过以下两种简洁方案实现仅在单个分面展示这两个元素:
方案一:绑定元素到指定分面(推荐)
利用tmap的图层关联特性,将指北针和比例尺仅绑定到目标分面对应的图层上:
library(tmap) library(stars) library(terra) # 读取数据 tif = system.file("tif/L7_ETMs.tif", package = "stars") x = rast(tif) # 绘制分面图,仅在最后一个分面添加指北针和比例尺 tm_shape(x) + tm_raster(style="quantile") + tm_facets(nrow = 3) + tm_layout( panel.labels = names(x), legend.outside = TRUE, legend.outside.position = "right", legend.position = c("center", "center"), legend.text.size = 1, legend.format = list(digits = 2, text.separator = "-") ) + # 仅针对最后一个分面添加元素 tm_shape(x[[nlyr(x)]]) + tm_compass(position = c("RIGHT", "BOTTOM")) + tm_scale_bar(text.size = 1, position = c("RIGHT", "BOTTOM"))
- 若要指定其他分面,只需将
x[[nlyr(x)]]替换为对应图层索引,比如x[[1]]对应第一个分面。
方案二:手动绘图添加元素
切换到绘图模式后,手动在目标位置添加指北针和比例尺:
library(tmap) library(stars) library(terra) # 读取数据 tif = system.file("tif/L7_ETMs.tif", package = "stars") x = rast(tif) # 切换到绘图模式 tmap_mode("plot") # 先绘制不带指北针和比例尺的分面图 p <- tm_shape(x) + tm_raster(style="quantile") + tm_facets(nrow = 3) + tm_layout( panel.labels = names(x), legend.outside = TRUE, legend.outside.position = "right", legend.position = c("center", "center"), legend.text.size = 1, legend.format = list(digits = 2, text.separator = "-") ) # 输出图形 print(p) # 手动在目标位置添加元素 tm_compass(position = c("RIGHT", "BOTTOM"))$draw() tm_scale_bar(text.size = 1, position = c("RIGHT", "BOTTOM"))$draw()
内容的提问来源于stack exchange,提问作者UseR10085
相关产品推荐
相关产品推荐

