How to control plot width in gridExtra?

user443854 picture user443854 · Jan 29, 2013 · Viewed 24.9k times · Source

Possible Duplicate:
left align two graph edges (ggplot)

I am trying to put two plots produced with ggplot on the same page, top and bottom, so that their widths are the same. The data is from the same time series, x axis being time, so it is important that data points with the same time are not shifted horizontally with respect to each other. I tried grid.arrange from package gridExtra:

grid.arrange(p1, p2)

but the plots have different widths due to different widths of y axis labels. I looked at this post that deals with similar problem, but I could not apply that information to solve my problem.

enter image description here

Answer

Justin picture Justin · Jan 29, 2013

The help text of grid.arrange says:

Arguments:

     ...: plots of class ggplot2, trellis, or grobs, and valid
          arguments to grid.layout

So reading grid.layout leads to:

Arguments:

    nrow: An integer describing the number of rows in the layout.

    ncol: An integer describing the number of columns in the layout.

  widths: A numeric vector or unit object describing the widths of the
          columns in the layout.

 heights: A numeric vector or unit object describing the heights of the
          rows in the layout.

In other words, you can pass widths and heights as vectors. grid.arrange(p1, p2, heights=c(1, 2). Or by way of an example:

dat <- data.frame(x=1:10, y=10:1)
q1 <- qplot(x, y, data=dat)
q2 <- qplot(y, x, data=dat)
q3 <- qplot(x, y, data=dat, geom='line')
q4 <- qplot(y, x, data=dat, geom='line')

grid.arrange(q1, q2, q3, q4, heights=1:2, widths=1:2)

It is also worth mentioning that a similar effect can often be accomplished using melt from the reshape2 package and facet_wrap or facet_grid in ggplot2.