竖向排列ggplot2图形

18

4
如果你想要在绘图面板中进行垂直和水平方向的对齐,我认为你最好先了解 gtable,然后你就可以在由 ggplot 返回的不太基础的 gtable 中添加新的 grobs、新的 viewports 等等。 - baptiste
非常感谢你,Baptiste!现在这个要点反映了你的答案。 - Etienne Low-Décarie
2个回答

30
这里有一个示例,可以对更基本的图形进行对齐:
library(ggplot2)
library(grid)
library(gtable)

p <- qplot(1,1)
g <- ggplotGrob(p)

panel_id <- g$layout[g$layout$name == "panel",c("t","l")]
g <- gtable_add_cols(g, unit(1,"cm"))

g <- gtable_add_grob(g, rectGrob(gp=gpar(fill="red")),
                     t = panel_id$t, l = ncol(g))

g <- gtable_add_rows(g, unit(1,"in"), 0)
g <- gtable_add_grob(g, rectGrob(gp=gpar(fill="blue")),
                     t = 1, l = panel_id$l)

grid.newpage()
grid.draw(g)

输入图片描述

并使用您的 grobs

输入图片描述


右侧的红色面板没有显示出来 - 是我的问题吗? :-| - PatrickT
1
@PatrickT ggplot2 经常在其内部结构中进行更改,从而破坏所有这样的解决方案。我已经更新了示例。 - baptiste

1

@baptiste的答案帮助我更好地理解了gtable结构以及如何修改它。下面是我修改后的代码片段,仅供(我自己)重用。

它使用find_panel()来获取面板范围,并将修改直接通过%>% 管道传递到grid.draw中。这种管道方式大大简化了对gtable_*函数的操作,因为它允许轻松取消注释单行并检查对最终图的影响。

library(ggplot2)
library(grid)
library(gtable)
library(dplyr)

p <- ggplot(tribble(~x,~y,~a,~b, 
                    1, 1, "a1","b1",
                    1, 1, "a2","b1",
                    1, 1, "a2","b2"), 
           aes(x=x,y=y)) + 
  geom_point() + 
  facet_grid(vars(a),vars(b))

g <- ggplotGrob(p)
panels_extent <- g %>% find_panel()
g %>%
  # Add red box to the very right, by appending a column and then filling it
  gtable_add_cols(widths = unit(1,"cm"), pos = -1) %>%
  gtable_add_grob(rectGrob(gp=gpar(fill="red")),
                  t = panels_extent$t, b = panels_extent$b,
                  l = -1, r = -1) %>%
  # Add green box to the top, by prepending a row and then filling it
  # Note the green box extends horizontally over the first panel as well 
  # as the space in between.
  gtable_add_rows(heights = unit(1,"cm"), pos = 0) %>%
  gtable_add_grob(rectGrob(gp=gpar(fill="green")),
                  t = 1, b = 1,
                  l = panels_extent$l, r = panels_extent$l+1) %>%
  {grid.newpage();grid.draw(.)}

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接