如何用cowplot创建带侧边/顶部标题及通用图例的Choropleth面板
解决方案
要实现带侧边标题、顶部标题和通用图例的2x2 Choropleth面板,可按以下步骤调整代码:
1. 调整图例生成函数,返回grob对象
tmap生成的图例需要转为grid图形对象(grob)才能与cowplot的布局函数兼容,修改图例函数:
create_legend <- function(data) { legend <- tm_shape(texas) + tm_borders() + tm_shape(CPC_grids_deviations) + tm_fill(col = data, palette = "Blues", title = "Count", style = "fixed", breaks = c(0, 1, 21, 41, 61, 81, 101, 121, 140)) + tm_layout(legend.only = TRUE, legend.position = c(0.5, 0.5)) return(tmap_grob(legend)) }
2. 生成所有图形组件
先生成四个地图grob和图例grob:
# 生成四个子地图 p1 <- create_grids_deviation_map("total_cpc_90") p2 <- create_grids_deviation_map("total_chirps_90") p3 <- create_grids_deviation_map("total_cpc_70") p4 <- create_grids_deviation_map("total_chirps_70") # 生成统一图例 legend_grob <- create_legend("total_cpc_90")
3. 构建带标题的布局
通过ggdraw和plot_grid逐步组合布局,添加列标题、侧边标题和整体标题:
library(cowplot) # 给顶部子图添加列标题(CPC/CHIRPS) p1_labeled <- ggdraw() + draw_plot(p1) + draw_text("CPC", x = 0.5, y = 1.02, size = 12, fontface = "bold") p2_labeled <- ggdraw() + draw_plot(p2) + draw_text("CHIRPS", x = 0.5, y = 1.02, size = 12, fontface = "bold") # 组合第一行,并添加侧边标题"90" row1 <- plot_grid(p1_labeled, p2_labeled, ncol = 2) row1_with_side <- ggdraw() + draw_plot(row1) + draw_text("90", x = -0.05, y = 0.5, angle = 90, size = 12, fontface = "bold") # 组合第二行,并添加侧边标题"70" row2 <- plot_grid(p3, p4, ncol = 2) row2_with_side <- ggdraw() + draw_plot(row2) + draw_text("70", x = -0.05, y = 0.5, angle = 90, size = 12, fontface = "bold") # 组合两行成主面板,添加整体顶部标题 main_panel <- plot_grid(row1_with_side, row2_with_side, nrow = 2, rel_heights = c(1, 1)) main_panel_with_title <- ggdraw(main_panel) + draw_text("Texas Deviation Counts", x = 0.5, y = 1.03, size = 14, fontface = "bold") # 最后整合主面板和图例,调整宽度比例 final_plot <- plot_grid(main_panel_with_title, legend_grob, ncol = 2, rel_widths = c(4, 1)) # 输出最终图形 print(final_plot)
关键说明
- 用
tmap_grob()转换tmap对象为grob,确保能被cowplot识别 - 通过
ggdraw()的draw_text()添加各类标题,angle = 90实现垂直侧边标题 - 调整
rel_widths和rel_heights参数控制各区域的尺寸比例,让布局更协调
内容的提问来源于stack exchange,提问作者Ramaraja
相关产品推荐
相关产品推荐

