【问题标题】:The perils of aligning plots in ggplot在 ggplot 中对齐图的危险
【发布时间】:2014-08-11 10:30:54
【问题描述】:

问题

如何组合不同的图 (ggplot2),具有不同的 y 轴和不同的图高度,但仍保持对齐?

详情

当使用 grid.arrange(方法 1)组合不同 y 轴单位的图时,它们不会对齐。解决此问题的一种方法是使用gtable(方法2),但我无法调整绘图的相对高度。

示例

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

方法1的结果是这个图,由于y轴标签的长度不同,所以没有对齐:

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

方法 2 导致绘图对齐,但我无法调整每个绘图的高度。

谢谢!

【问题讨论】:

标签: r ggplot2 alignment gridextra gtable


【解决方案1】:

在您的 gtable g 中,您可以设置相对面板高度,

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)

【讨论】:

  • 工作完美,比 grid.arrange 方法好得多。谢谢。
  • 感谢您的精彩回答!但也许网格更新发生了一些变化,但现在(版本 3.3.0)要使其正常工作,第二行必须是:g$heights[panels] &lt;- unit(c(2,1), "null")
  • @RNoob 正确,在网格和 ggplot2 中,该级别的情况都发生了变化
猜你喜欢
  • 1970-01-01
  • 2018-09-04
  • 2017-03-11
  • 2011-03-07
  • 2021-08-24
  • 1970-01-01
  • 2011-07-23
  • 1970-01-01
  • 2011-11-09
相关资源
最近更新 更多