12

I have two ggplots on the same page, and I'd like their panels to be the same width.

Some sample data:

dfr1 <- data.frame(
  time = 1:10,
  value = runif(10)  
)

dfr2 <- data.frame(
  time = 1:10,
  value = runif(10, 1000, 1001)  
)

One plot below the other:

p1 <- ggplot(dfr1, aes(time, value)) + geom_line()
p2 <- ggplot(dfr2, aes(time, value)) + geom_line()

grid.newpage()
pushViewport(viewport(layout = grid.layout(2, 1)))   
print(p1, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))         
print(p2, vp = viewport(layout.pos.row = 2, layout.pos.col = 1))

How do I specify the panel widths and positions in each plot, in order to make them line up?

(I don't want to combine the plots with faceting; it isn't appropriate in my real-world example.)

Richie Cotton
  • 118,240
  • 47
  • 247
  • 360
  • I don't know any of the details, but `gridExtra` probably has something to help you: http://cran.r-project.org/web/packages/gridExtra/gridExtra.pdf – Chase Mar 30 '11 at 17:05
  • 1
    This definitely helps: http://stackoverflow.com/questions/13294952/left-align-two-graph-edges-ggplot – Etienne Low-Décarie Mar 21 '13 at 18:48
  • @EtienneLow-Décarie -- Yes, great find! That's essentially the answer. It would be nice, though, to have a function that wraps up those steps, if it's to be used as more than a one-off (and, potentially, for many more than 2 plots). – Josh O'Brien Mar 21 '13 at 19:44

1 Answers1

13

Original solution:

 #   install.packages("ggExtra", repos="http://R-Forge.R-project.org")
 #   library(ggExtra)
 #   align.plots(p1, p2)

Edit (22/03/13):

Since ggExtra doesn't exist anymore (and many internals of ggplot2 have changed), it's better to use the merging functions (rbind, cbind) provided by the gtable package,

gl = lapply(list(p1,p2), ggplotGrob)     
library(gtable)
g = do.call(rbind, c(gl, size="first"))
g$widths = do.call(unit.pmax, lapply(gl, "[[", "widths"))

grid.newpage()
grid.draw(g)    

enter image description here

baptiste
  • 75,767
  • 19
  • 198
  • 294
Andrie
  • 176,377
  • 47
  • 447
  • 496
  • Just realised that you had mentioned `align.plots` to me in a previous question. http://stackoverflow.com/questions/5409776/how-to-order-bars-in-faceted-ggplot2-bar-chart I promise I'll remember it this time! – Richie Cotton Mar 31 '11 at 13:49
  • ggExtra is no longer online (https://groups.google.com/forum/?fromgroups#!topic/ggplot2-dev/4dKg-qA7eZE). – Etienne Low-Décarie Mar 21 '13 at 18:23
  • indeed, this package was retired – baptiste Mar 21 '13 at 20:18
  • 1
    @baptiste Thank you for the edit. Are you sure you don't want to post this as a new answer? – Andrie Mar 22 '13 at 04:37
  • i initially posted an answer with the full code, but then yours needed editing anyway. It's fine like this (at least for now, until the code breaks again...) – baptiste Mar 22 '13 at 10:00