Specifying ggplot2 panel width
Asked Answered
K

1

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.)

Kampmeier answered 30/3, 2011 at 16:33 Comment(3)
I don't know any of the details, but gridExtra probably has something to help you: cran.r-project.org/web/packages/gridExtra/gridExtra.pdfKine
This definitely helps: #13295452Nacre
@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).Blizzard
P
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

Possessed answered 30/3, 2011 at 20:58 Comment(5)
Just realised that you had mentioned align.plots to me in a previous question. #5410276 I promise I'll remember it this time!Kampmeier
ggExtra is no longer online (groups.google.com/forum/?fromgroups#!topic/ggplot2-dev/…).Nacre
indeed, this package was retiredDebility
@Debility Thank you for the edit. Are you sure you don't want to post this as a new answer?Possessed
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...)Debility

© 2022 - 2024 — McMap. All rights reserved.