使用gtable创建ggplot图(具有相同宽度的凹槽)以创建2x2布局

nof*_*lly 4 r ggplot2 grob gtable

我试图使用grobs和gtable将4(ggplot2)图排列成2x2网格.我不知道如何设置宽度,也不知道非1xn或nx1排列.

使用此代码:

data(iris)
a <- ggplot(iris, aes(x=Species, y=Petal.Width)) + geom_boxplot(color="black") + ylab(expression(Foo~Bar~(g~cm^{-3})))
b <- ggplot(iris, aes(x=Species, y=Petal.Length*100)) + geom_boxplot(color="black") + ylab("foobar (mm)")
c <- ggplot(iris, aes(x=Species, y=Sepal.Width)) + geom_boxplot(color="black") + ylab("foobar (%)")
d <- ggplot(iris, aes(x=Species, y=log10(Sepal.Length))) + geom_boxplot(color="black") + ylab("foobar (cm)")

plots <- list(a,b,c,d)
grobs = lapply(plots, ggplotGrob)
g = do.call(rbind, c(grobs, size="first"))

g$widths = do.call(unit.pmax, lapply(grobs, "[[", "widths"))
grid.newpage()
grid.draw(g)
Run Code Online (Sandbox Code Playgroud)

我可以创建以下1x4安排. 1乘4的情节安排

如果我将grid.arrange用于两列,则在4个图上,这些图的宽度不同.

4乘4的绘图排列 - 不等宽度

如何将图表绑定到4 x 4排列的gtable中?

# I thought maybe I could cbind, then rbind, but this does not work
plots1 <- list(a,b)
plots2 <- list(c,d)
grobs1 = lapply(plots1, ggplotGrob)
grobs2 = lapply(plots2, ggplotGrob)

g1 = do.call(cbind, c(grobs1, size="first"))
g2 = do.call(cbind, c(grobs2, size="first"))
# g3 = do.call(rbind, c(g1,g2, size="first")) #this does not work
Run Code Online (Sandbox Code Playgroud)

osh*_*hun 11

我想你已经有了答案.
您的最后一行会返回一个错误,但是一个小的编辑会产生一个组合图,其中列中的宽度相同:

g3 = do.call(rbind, c(list(g1,g2), size="first")) #combine g1 and g2 into a list G3

美学/参考的旁注:
如果您的x轴是相同的,您可以从顶部的两个图中删除它.

library(ggplot2); library(gridExtra); library(grid)

# Tweak the margins to use up empty space.  Margins: Top, Right, Bottom, Left
# For reference: a1= top left,    b1= top right 
#                c1= bottom left, d1= bottom right
a1 <- a + theme(axis.title.x = element_blank(), 
                axis.text.x = element_blank(), 
                axis.ticks.x= element_blank(), 
                plot.margin= unit(c(1, 1, -0.5, 0.5), "lines") ) 
b1 <- b + theme(axis.title.x = element_blank(), 
                axis.text.x = element_blank(), 
                axis.ticks.x= element_blank(), 
                plot.margin= unit(c(1, 1, -0.5, 0.5), "lines") ) 
c1 <- c + theme(plot.margin= unit(c(0, 1, 0.5, 0.5), "lines") )  
d1 <- d + theme(plot.margin= unit(c(0, 1, 0.5, 0.5), "lines") )  

grobz <- lapply(list(a1, b1, c1, d1), ggplotGrob)
grobz.plot <- arrangeGrob( grobs = list(rbind(grobz[[1]], grobz[[3]], size = "last"),
                                        rbind(grobz[[2]], grobz[[4]], size = "last")),
                           ncol = 2)
grid.draw(grobz.plot)
Run Code Online (Sandbox Code Playgroud)

grobz

这些StackOverflow问题有助于对齐图:

  • rbind在gtable中使用设置绘图宽度(Baptiste)[ 链接 ]
  • gtable中的相对面板高度(Baptiste)[ 链接 ]
  • 绘图宽度和图例[ 链接 ]