The perils of aligning plots in ggplot
Asked Answered
A

1

17

QUESTION

How do you combine separate plots (ggplot2), with different y-axis and different plot heights, yet retain alignment?

DETAIL

When combining plots with grid.arrange (method1), with different y-axis units, they do not align. One way around this is to use gtable (method2), but I cannot adjust the relative height of the plots.

EXAMPLE

require(ggplot2)

#Make two plots, with different y axis
  x = c(1, 5)
  y= c(.1, .4)
  data1<-data.frame(x,y)
  top<-
    ggplot(data1, aes(x=x, y=y))+
    geom_line()

  x = c(1, 5)
  y= c(100000, 400000)
  data2<-data.frame(x,y)
  bottom<-
    ggplot(data2, aes(x=x, y=y))+
    geom_line()


# Method 1 - Grid Extra 
  require(gridExtra)
  grid.arrange(top, bottom, heights=c(.6,.3))

Method 1 results in this plot, which is misaligned due to the different length y axis labels:

enter image description here

#Method 2 - gtable
  require(gtable)
  #Extract Grobs
  g1<-ggplotGrob(top)
  g2<-ggplotGrob(bottom)
  #Bind the tables
  g<-gtable:::rbind_gtable(g1, g2, "first")
  #Remove a row between the plots
  g <- gtable_add_rows(g, unit(-1,"cm"), pos=nrow(g1))
  #draw
  grid.newpage()
  grid.draw(g)

Method 2 results in aligned plots, but I cannot adjust the height of each plot. enter image description here

THANKS!

Acetous answered 20/6, 2014 at 15:47 Comment(1)
This might helpStopcock
S
19

In your gtable g, you can set the relative panel heights,

require(gtable)
g1<-ggplotGrob(top)
g2<-ggplotGrob(bottom)
g<-gtable:::rbind_gtable(g1, g2, "first")
panels <- g$layout$t[grep("panel", g$layout$name)]
g$heights[panels] <- unit(c(1,2), "null")

grid.newpage()
grid.draw(g)
Squirm answered 20/6, 2014 at 18:27 Comment(3)
Works flawlessly, and much better results than the grid.arrange method. Thanks.Acetous
Thanks for the great answer! But perhaps something changed in updates of grid, but now (version 3.3.0) for this to work the second line must be: g$heights[panels] <- unit(c(2,1), "null")Accursed
@RNoob correct, things have changed at that level in both grid and ggplot2Squirm

© 2022 - 2024 — McMap. All rights reserved.