如何在R语言tmap绘图中为子图标题添加边框?
在tmap中为子图标题添加边框的解决方案
tmap的tm_layout函数确实没有直接设置子图标题边框的参数,不过可以通过两种方法实现需求:
方法1:使用grid包手动绘制边框
适合直接基于tmap的子图布局,手动定位标题位置并添加边框:
library(tmap) library(grid) data(World) # 创建两个带标题的子图 map1 <- tm_shape(World) + tm_fill("pop_est") + tm_layout(title = "Population Estimate", title.position = c("left", "top"), # 固定标题位置方便定位 title.size = 1) map2 <- tm_shape(World) + tm_borders() + tm_layout(title = "Country Borders", title.position = c("left", "top"), title.size = 1) # 排列子图 tmap_arrange(map1, map2) # 给第一个子图标题加边框:调整x/y/width/height适配你的标题 grid.rect(x = 0.22, y = 0.94, width = 0.22, height = 0.05, gp = gpar(lwd = 1, fill = NA, col = "black")) # fill=NA表示透明背景 # 给第二个子图标题加边框 grid.rect(x = 0.72, y = 0.94, width = 0.22, height = 0.05, gp = gpar(lwd = 1, fill = NA, col = "black"))
说明:
title.position必须固定,否则无法准确定位边框位置x/y是边框的中心坐标,width/height是边框尺寸,需要根据你的标题长度和布局微调gpar()参数可以自定义边框颜色(col)、线宽(lwd)、背景填充色(fill)
方法2:使用patchwork+ggplot2实现自动适配的标题边框
将tmap对象转为ggplot对象后,利用ggplot的主题系统设置带边框的标题,布局更灵活:
library(tmap) library(patchwork) library(ggplot2) data(World) # 将tmap转为ggplot对象,并设置标题样式 map1 <- as.ggplot(tm_shape(World) + tm_fill("pop_est")) + labs(title = "Population Estimate") + theme(plot.title = element_text( box.colour = "black", # 边框颜色 box.size = 1, # 边框线宽 box.fill = "white", # 标题背景色 padding = margin(5, 10, 5, 10), # 文字与边框的间距 margin = margin(b = 8), # 标题与地图的间距 size = 10 )) map2 <- as.ggplot(tm_shape(World) + tm_borders()) + labs(title = "Country Borders") + theme(plot.title = element_text( box.colour = "black", box.size = 1, box.fill = "white", padding = margin(5, 10, 5, 10), margin = margin(b = 8), size = 10 )) # 组合子图(可自定义布局比例) map1 + map2 + plot_layout(ncol = 2)
说明:
- 这种方法会自动适配标题的长度,不需要手动调整位置
- 通过
element_text()的参数可以精细控制边框样式、背景色、间距等 - 支持patchwork的所有布局功能,比如调整列数、子图比例等
内容的提问来源于stack exchange,提问作者Phil
相关产品推荐
相关产品推荐

