cowplot包plot_grid排列子图无法实现p2与p1左对齐如何解决
问题原因
plot_grid()的align、axis参数仅能对齐不同ggplot对象的绘图面板边界,管不到你通过annotation_custom()嵌在ggplot内部的自定义元素位置,之前的调整没效果核心是两个点:
p2用了theme_void(),没有坐标轴、标签这类占边距的元素,绘图面板本身就铺满了p2的整个画布,和p1的面板宽度本来就是对齐的,再调对齐参数自然不会有变化- 嵌进去的flextable栅格在调用
rasterGrob()时默认是水平居中的,这个内部位置cowplot的对齐参数控制不了,所以最终表格看起来是居中的,和p1的左边界对不上。
解决方法
两种常用方案选一种即可:
方案1:调整p2内部元素对齐+匹配边距
直接修改p2的构建代码,让内部表格左对齐,同时给p2加上和p1匹配的左侧留白,不需要额外调整plot_grid参数:
library(ggplot2) library(flextable) library(grid) library(cowplot) library(tidyverse) mydf <- tibble(a = c(1,2,3,4,5,4), b = c(4,4,4,3,3,3)) p1 <- mydf %>% ggplot(aes(x = a, y = b, color = as.factor(b))) + geom_point() ft_raster <- mydf %>% flextable::flextable() %>% as_raster() # 修改后的p2 p2 <- ggplot() + theme_void() + annotation_custom( # 关键修改:设置栅格左对齐,取消默认居中 rasterGrob(ft_raster, x = unit(0, "npc"), hjust = 0), xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf ) + # 关键修改:给p2加上和p1匹配的左侧边距,可根据自己图的字号、边距微调数值 theme(plot.margin = margin(l = 42, unit = "pt")) # 直接组合即可,不需要加align/axis参数 cowplot::plot_grid(p1, p2, nrow = 2, ncol = 1, rel_heights = c(1, 1))
方案2:手动定位布局,无需空ggplot嵌表格
不用构建空的p2对象,直接用cowplot的自由布局功能放置表格,还能自动匹配p1的左侧边距,不用手动调数值:
# 转换为可自由放置的grob对象 p1_grob <- ggplotGrob(p1) ft_grob <- rasterGrob(ft_raster, hjust = 0) # 自动计算p1绘图面板距离画布左边缘的距离 left_margin <- grep("ylab-l|axis-l", p1_grob$layout$name) %>% map_dbl(~p1_grob$widths[.x] %>% convertWidth("npc", valueOnly = TRUE)) %>% sum() # 组合绘图 ggdraw() + # 上半部分放p1 draw_grob(p1_grob, x = 0, y = 0.5, width = 1, height = 0.5) + # 下半部分放表格,自动和p1绘图区左对齐 draw_grob(ft_grob, x = left_margin, y = 0.05, width = 1 - left_margin - 0.03, height = 0.4)
内容的提问来源于stack exchange,提问作者zhiwei li
相关产品推荐
相关产品推荐

