使用gridExtra在Rmarkdown knitr-HTML中保持图表大小一致

4
我正在使用 gridExtra 包中的 grid.arrange() 函数绘制 4 个由 ggplot2 生成的图形。整体使用 RStudio 中的 RMarkdown 工作,并通过 knitr 包呈现为 HTML 格式。
 g1 <- ggplot(); g2 <- ggplot(); g3 <- ggplot(); g4 <- ggplot()
 grid.arrange(g1,g2,g3,g4,ncol=2,nrow=2)

RMarkdown/knitr 中,我使用了以下选项:

   output: 
   html_document:
   keep_md: true

 ```r,figures, fig.align='center',fig.width=12,fig.height=10```

问题:这4个数字虽然按照需要绘制,但大小明显不成比例。

已尝试的解决方案:在此问题中提出,但效果不佳。

编辑:现在提供可重现的示例,并附带html输出屏幕截图。

```{r mtcars plots, fig.align='center',fig.width=9,fig.height=7}
   library(datasets)
   library(ggplot2)
   library(gridExtra)
   g1 <- ggplot(mtcars, aes(drat,carb*100)) + geom_point(color="blue") 
   g2 <- ggplot(mtcars, aes(mpg,hp)) + geom_point(color="red")
   g3 <- ggplot(mtcars, aes(qsec,wt)) + geom_point(color="green")
   g4 <- ggplot(mtcars, aes(carb,disp*100)) + geom_point(color="orange")+
         labs(y="This is the lab for 'disp' fairly long until here") 
   grid.arrange(g1,g2,g3,g4,ncol=2,nrow=2,
         top=textGrob("MTCARS: Everything about cars...!",
                      gp=gpar(fontsize=16,font=1)))
   ```

这里输入图片描述

这里的效果比真实数据略微微妙。请注意“绿色”和“橙色”图形的对齐。

任何帮助将不胜感激。


怎么样?有些有图例,而有些没有吗?如果有一个示例和输出或屏幕截图会更有意义。 - rawr
@rawr:单个图表只有坐标轴标签。我会看看能否使用R数据集生成一张截图。 - remi
1个回答

3
您可以使用gtable来实现此功能,
library(gtable)
library(grid)
pl <- lapply(list(g1,g2,g3,g4), ggplotGrob)
g12 <- cbind(pl[[1]], pl[[2]], size="first")
g12$heights <- unit.pmax(pl[[1]][["heights"]], pl[[2]][["heights"]])
g34 <- cbind(pl[[3]], pl[[4]], size="first")
g34$heights <- unit.pmax(pl[[3]][["heights"]], pl[[4]][["heights"]])
g1234 <- rbind(g12, g34, size="first")
g1234$widths <- unit.pmax(g12[["widths"]], g34[["widths"]])
grid.newpage()
grid.draw(g1234)

@ baptiste:非常好用。感谢您的解决方案。这些包感觉很底层,真的很不错。我只需要添加一个链接到您之前的贡献,以便在gtable/plot中添加主标题。链接 - remi

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