Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The perils of aligning plots in ggplot

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!

like image 695
wab Avatar asked Jun 20 '14 15:06

wab


1 Answers

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)
like image 183
baptiste Avatar answered Nov 06 '22 19:11

baptiste