How to control plot width in gridExtra? [duplicate]

狂风中的少年 提交于 2019-11-30 09:26:25

As per my comment (and also the comment in the middle of the @Justin answer) facet_wrap may be the way to go. It generates something like the image below. Obviously you'd need to play around with colours, legends and maybe the order of the factors, but you can see the general approach. Code follows image.

library(ggplot2)
library(reshape)

mydf <- data.frame(day = 1:10,
                   upper1 = runif(10, 10000, 20000),
                   upper2 = runif(10, 15000, 16000),
                   lower1 = runif(10, 1, 10),
                   lower2 = runif(10, 3, 8))

mydf.melt <- melt(mydf, id.var = 'day')
mydf.melt$grouping <- ifelse(mydf.melt$value >= 10000, "upper", "lower")

ggplot(mydf.melt, aes(x = day, y = value, group = variable)) +
       geom_line() +
       facet_wrap(~ grouping, ncol = 1, scales = "free_y")

The help text of grid.arrange says:

Arguments:

     ...: plots of class ggplot2, trellis, or grobs, and valid
          arguments to grid.layout

So reading grid.layout leads to:

Arguments:

    nrow: An integer describing the number of rows in the layout.

    ncol: An integer describing the number of columns in the layout.

  widths: A numeric vector or unit object describing the widths of the
          columns in the layout.

 heights: A numeric vector or unit object describing the heights of the
          rows in the layout.

In other words, you can pass widths and heights as vectors. grid.arrange(p1, p2, heights=c(1, 2). Or by way of an example:

dat <- data.frame(x=1:10, y=10:1)
q1 <- qplot(x, y, data=dat)
q2 <- qplot(y, x, data=dat)
q3 <- qplot(x, y, data=dat, geom='line')
q4 <- qplot(y, x, data=dat, geom='line')

grid.arrange(q1, q2, q3, q4, heights=1:2, widths=1:2)

It is also worth mentioning that a similar effect can often be accomplished using melt from the reshape2 package and facet_wrap or facet_grid in ggplot2.

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