【问题标题】:Consistent figures size with gridExtra in Rmarkdown knitr-HTML与 Rmarkdown knitr-HTML 中的 gridExtra 一致的数字大小
【发布时间】:2015-09-25 10:36:32
【问题描述】:

我正在使用gridExtragrid.arrange() 函数来绘制由ggplot2 生成的4 个数字。整个是用knitr 包使用RMarkdown 在RStudio 上工作的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 个数字是根据需要绘制的,但大小明显不成比例。

经过测试的解决方案:在此question 中提出,但没有取得多大成功。

编辑:现在提供带有 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:个别地块只有轴标签。我将看看是否可以使用其中一个 R 数据集生成屏幕截图。

标签: html r knitr r-markdown gridextra


【解决方案1】:

您可以为此使用 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:效果很好。感谢您解决它。非常不错的包,带有低级的感觉。我将添加一个指向您的previous contribution 的链接,以便将主标题添加到 gtable/plot。
猜你喜欢
  • 2015-12-02
  • 1970-01-01
  • 2015-12-15
  • 1970-01-01
  • 2014-10-28
  • 2013-09-09
  • 1970-01-01
  • 2013-05-28
  • 2016-03-19
相关资源
最近更新 更多