r - 如何按标题而不是绘图区域对齐多个绘图?

标签 r ggplot2 gridextra cowplot

我正在使用 egg 对齐页面上的多个绘图。我想知道是否可以按标题对齐两列 a)c)而不是情节区域?谢谢!

代码:

library(egg)
library(grid)

p1 <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) +
  geom_point() + ggtitle("a)")
p1

p2 <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) +
  geom_point() + facet_wrap(~ cyl, ncol = 2, scales = "free") +
  guides(colour = "none") +
  theme() + ggtitle("b)")
p2

p3 <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) +
  geom_point() + facet_grid(. ~ am, scales = "free") + guides(colour="none") +
  ggtitle("c)")
p3

g1 <- ggplotGrob(p1)

g2 <- ggplotGrob(p2)

g3 <- ggplotGrob(p3)

fg1 <- gtable_frame(g1, debug = TRUE)
fg2 <- gtable_frame(g2, debug = TRUE)
fg12 <- gtable_frame(gtable_rbind(fg1, fg2),
                     width = unit(2, "null"),
                     height = unit(1, "null"))
fg3 <-
  gtable_frame(
    g3,
    width = unit(2, "null"),
    height = unit(1, "null"),
    debug = TRUE
  )
grid.newpage()
combined <- gtable_cbind(fg12, fg3)
grid.draw(combined)  

剧情:

enter image description here

最佳答案

我通过使用 cowplot 找到了另一种方法包裹

left_col <- cowplot::plot_grid(p1 + ggtitle(""), p2 + ggtitle(""), 
                               labels = c('a)', 'b)'), label_size = 14,
                               ncol = 1, align = 'v', axis = 'lr') 
cowplot::plot_grid(left_col, p3 + ggtitle(""), 
                   labels = c('', 'c)'), label_size = 14,
                   align = 'h', axis = 'b')

enter image description here

另见 here

编辑:

最近开发的包 patchwork ggplot2也可以完成工作
library(patchwork)

{
  p1 + {p2} + patchwork::plot_layout(ncol = 1)
} / p3 + patchwork::plot_layout(ncol = 2)

enter image description here

关于r - 如何按标题而不是绘图区域对齐多个绘图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47667729/

相关文章:

R - 计算 bin 中特定值的数量

r - 使用 ggplot 的条形图重新排序无法正常工作

r - 计算向量中的 NA,但开头除外

R ggplot2 : How to draw geom_points that have a solid color and a transparent stroke and are colored depending on color?

R ggplot2 : legend should be discrete and not continuous

从整个数据框中删除一个字符

r - 用R中的ggplot2在合并的类中绘制连续栅格数据

r - 在 R 中,如何存储插图以便稍后使用 grid.arrange 进行排列?

r - 如何绘制和保存 tableGrob 对象

r - 无法从 gridExtra 禁用 R markdown 输出(附加注释)