remi remi - 5 months ago 33
HTML Question

Consistent figures size with gridExtra in Rmarkdown knitr-HTML

I am using the

gridExtra
package
grid.arrange()
function to plot 4 figures generated by
ggplot2
. The whole is html-rendered with the
knitr
package using
RMarkdown
working on RStudio.

In a nutshell:

g1 <- ggplot(); g2 <- ggplot(); g3 <- ggplot(); g4 <- ggplot()
grid.arrange(g1,g2,g3,g4,ncol=2,nrow=2)


In
RMarkdown/knitr
, I am using these options:

output:
html_document:
keep_md: true

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


The problem: the 4 figures are plotted as needed but are clearly disproportionate in size.

Tested solutions: proposed in this question without much success.

EDIT: now providing reproducible example with html output screen cap.

```{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)))
```


enter image description here

The effects are slightly more subtle than it is with real data. Note alignment of "green" and "orange" plots.

Any help would be much appreciated.

Answer

You can use gtable for this,

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)