如何在R的tmap分面图中为每个面板添加对应数据注释?
tmap分面图实现单面板对应注释的解决方法
问题描述
我在使用R语言tmap包创建分面栅格图时,尝试为每个面板添加对应图层的均值(Mean)和标准差(SD)注释,但所有面板都重叠显示了所有注释,如何让每个面板仅显示自身对应的注释?
可复现代码:
library(tmap) library(stars) library(terra) library(tidyverse) # 提供pivot_longer等数据处理函数 # 读取测试数据 tif = system.file("tif/L7_ETMs.tif", package = "stars") x = terra::rast(tif) # 计算每个栅格图层的均值和标准差 summ <- x |> as.data.frame() |> pivot_longer(everything()) |> group_by(name) |> summarise(Mean = mean(value, na.rm = TRUE), SD = sd(value, na.rm = TRUE)) %>% mutate(across(c(Mean, SD), ~round(., 3))) %>% mutate(lab = paste0("Mean = ", Mean, "\nSD = ", SD)) %>% dplyr::select(name, lab) # 设置注释的显示位置(左下角偏移) bbox <- st_bbox(x) annotations <- summ %>% mutate( x = bbox["xmin"] + 0.05 * (bbox["xmax"] - bbox["xmin"]), y = bbox["ymin"] + 0.1 * (bbox["ymax"] - bbox["ymin"]) ) # 转换为sf空间对象 annotations_sf <- st_as_sf(annotations, coords = c("x", "y"), crs = st_crs(x)) # 绘制基础分面栅格图 map <- tm_shape(x) + tm_raster(style="quantile") + tm_facets(nrow = 3) + tm_layout(panel.labels = names(x), attr.outside = T, attr.outside.position = "bottom", attr.just = "right", legend.outside = T, legend.outside.position = "right", legend.position = c("left", "top"), legend.text.size = 0.8, legend.title.size = 0.9, legend.format = list(digits = 2, text.separator = "-"))+ tm_compass(position = c("left", "top"))+ tm_scale_bar(text.size = 1, position = c("RIGHT", "top"))
解决方法
核心是让注释图层遵循和栅格图层一致的分面规则,通过为注释图层添加tm_facets(by = "name"),将每个注释分配到对应名称的面板中:
修改后的注释添加代码:
map + tm_shape(annotations_sf) + tm_text("lab", xmod = 0.05, ymod = -0.05, col = "black", just = "left", size = 1) + tm_facets(by = "name", free.coords = FALSE)
关键参数说明
by = "name":根据注释数据中的name字段,将注释匹配到同名的栅格面板free.coords = FALSE:强制所有面板使用相同的坐标范围,避免注释位置偏移
内容的提问来源于stack exchange,提问作者UseR10085
相关产品推荐
相关产品推荐

