使用grid.arrange在ggplots之后添加空格

时间:2014-08-18 22:05:50

标签: r ggplot2 gridextra

我在循环中创建ggplots,然后使用grid.arrange在格子类型图形中的一个页面上绘制我的每个图形。我遇到的问题是我在每个图周围都有一个边框,当我绘制它们时它们会合并在一起。有谁知道如何在数字之间添加空白。我已经查找了有关人物填充的信息,还试图在我的情节之间添加空白geom_rect,但到目前为止还没有运气。下面提供了一些简化代码。感谢您提供的任何帮助。

p = vector("list", 3) #List for arranging grid

for(ii in 1:3){
  p[[ii]] = ggplot(mtcars, aes(x = wt, y = mpg))+
    geom_point()+
    theme(plot.background = element_rect(colour = 'black', size = 2))
}
do.call("grid.arrange", c(p, ncol=1))

2 个答案:

答案 0 :(得分:2)

我尝试了很多不同的努力,使视口在3 x 1布局中更小,最后意识到只需在5 x 1布局中添加一些具有窄高度的空白区域就很容易了:

Layout <- grid.layout(nrow = 5, ncol = 1, 
                      heights=c(1, .1, 1, .1, 1) )
# could have written code to alternate heights or widths with gaps
grid.show.layout(Layout)
vplayout <- function(...) {  # sets up new page with Layout
     grid.newpage()
     pushViewport(viewport(layout = Layout))
 }

subplot <- function(x, y) viewport(layout.pos.row = x,
     layout.pos.col = y)

mmplot <- function(p=p) { # could make more general
     vplayout()
     print(p[[1]], vp = subplot(1, 1 ))
     print(p[[2]], vp = subplot(3, 1))
     print(p[[3]], vp = subplot(5, 1 ))
 }

mmplot(a, z)

enter image description here

答案 1 :(得分:1)

或者,这个experimental version of gtable提供了与grid.arrange类似的接口,

library(ggplot2)
library(gtable)

lp <- replicate(3, qplot(rnorm(10), rnorm(10)) + 
                     theme(plot.background=element_rect(size = 3, colour="black")),
                simplify = FALSE)

lg <- lapply(lp, ggplotGrob)
g <- do.call(gtable_arrange, c(lg, ncol=1, draw=FALSE))
g <- gtable_add_rows(g, heights = unit(1, "line"), pos = 1)
g <- gtable_add_rows(g, heights = unit(1, "line"), pos = 3)
grid.newpage()
grid.draw(g)