The perils of aligning plots in ggplot

喜你入骨 提交于 2019-12-17 10:49:11

问题


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:

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

THANKS!


回答1:


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)


来源:https://stackoverflow.com/questions/24331107/the-perils-of-aligning-plots-in-ggplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!