调整地块ggplot的危险

调整地块ggplot的危险

本文介绍了调整地块ggplot的危险的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何结合不同的地块(GGPLOT2),具有不同的Y轴和不同情节的高度,但仍保留对齐?

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

详细信息

在结合地块与 grid.arrange (方法1),具有不同的y轴的单位,他们不对齐。解决此问题的方法是使用 gtable (方法2),但我无法调整该地块的相对高度。

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.

示例

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

方法2的结果一致的地块,但我不能调整每个情节的高度。

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

谢谢!

推荐答案

在你gtable 先按g ,你可以设置相对面板的高度,

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

 panels <- g$layout$t[grep("panel", g$layout$name)]
 g$heights[panels] <- lapply(c(1,2), unit, "null")

这篇关于调整地块ggplot的危险的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 00:15