4

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.

Community
  • 1
  • 1
remi
  • 781
  • 2
  • 13
  • 22
  • how so? do some have legends and others do not? this would make more sense with an example and output or a screenshot – rawr Sep 25 '15 at 12:46
  • @rawr: individual plots only have axis labels. I will see if I can generate a screenshot with one of R datasets. – remi Sep 25 '15 at 13:29

1 Answers1

3

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)
baptiste
  • 75,767
  • 19
  • 198
  • 294
  • @ baptiste: works great. Thanks for solving it. Really nice packs with a low-level feel to it. I'll just add a link to your [previous contribution](http://stackoverflow.com/questions/11774703/adding-text-to-a-grid-table-plot) for adding the main title to the gtable/plot. – remi Oct 01 '15 at 01:34