如何在R语言tmap中重新排序栅格图分面?
调整tmap栅格分面排列顺序的方法
要让tmap的分面按指定时间顺序排列,最直接的方式是重新调整栅格对象的波段顺序——因为tmap的分面默认遵循栅格波段的排列顺序。具体实现步骤如下:
- 定义你需要的目标顺序列表
- 基于该列表重新提取栅格的波段,生成新的有序栅格对象
- 绘制时使用新的栅格对象,并同步更新面板标签
修改后的完整代码如下:
library(tmap) library(stars) library(terra) # 读取数据 tif = system.file("tif/L7_ETMs.tif", package = "stars") x = rast(tif) # 分配假名称 names(x) <- c("RF_04.Apr.2022_LL", "RF_13.Dec.2021_LL", "RF_15.Feb.2022_LL", "RF_17.Dec.2020_LL", "RF_18.Nov.2021_LL", "RF_19.Feb.2021_LL") # 指定目标时间顺序 target_order <- c("RF_17.Dec.2020_LL", "RF_19.Feb.2021_LL", "RF_18.Nov.2021_LL", "RF_13.Dec.2021_LL", "RF_15.Feb.2022_LL", "RF_04.Apr.2022_LL") # 重新排列栅格波段 x_reordered <- x[[target_order]] # 绘制分面图 tm_shape(x_reordered) + tm_raster(style="quantile")+ tm_facets(nrow = 3) + tm_layout(panel.labels = target_order, legend.outside=T, legend.outside.position = "right", legend.position= c("center", "center"), legend.text.size = 1, legend.format = list(digits = 2, text.separator = "-") )+ tm_compass(position = c("LEFT", "BOTTOM"))+ tm_scale_bar(breaks = c(0, 0.5), text.size = 1, position = c("LEFT", "BOTTOM"))
关键说明
- 使用
x[[target_order]]通过波段名称重新排序,这种方式直观且不易出错,尤其适合波段名称带有明确标识的场景。 - 同步修改
panel.labels为target_order,确保每个分面的标签与对应栅格数据完全匹配。
内容的提问来源于stack exchange,提问作者UseR10085
相关产品推荐
相关产品推荐

