【问题标题】:How to control plot width in gridExtra? [duplicate]如何控制gridExtra中的绘图宽度? [复制]
【发布时间】:2013-01-29 18:51:54
【问题描述】:

可能重复:
left align two graph edges (ggplot)

我试图将使用ggplot 生成的两个图放在同一页面的顶部和底部,以便它们的宽度相同。数据来自相同的时间序列,x 轴是时间,因此具有相同时间的数据点不会相对于彼此水平移动,这一点很重要。我从包 gridExtra 中尝试了grid.arrange

grid.arrange(p1, p2)

但由于 y 轴标签的宽度不同,这些图的宽度也不同。我查看了处理类似问题的this post,但我无法应用该信息来解决我的问题。

【问题讨论】:

  • @user443854 我曾经花了几个小时试图做到这一点。我成功了,但后来才意识到它是faceting 的完美应用程序。如果这两个数据共享相同的 x 轴,那么它应该很容易。是的。

标签: r ggplot2 gridextra


【解决方案1】:

grid.arrange的帮助文字说:

Arguments:

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

所以阅读grid.layout会导致:

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.

换句话说,您可以将宽度和高度作为向量传递。 grid.arrange(p1, p2, heights=c(1, 2)。或者举个例子:

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)

还值得一提的是,通常可以使用reshape2 包中的meltggplot2 中的facet_wrapfacet_grid 来实现类似的效果。

【讨论】:

  • 我之前尝试过widths。要了解为什么这不起作用,请尝试使用 q1 &lt;- qplot(x, y*1000, data=dat),然后尝试 grid.arrange(q1, q2, q3, q4, heights=1:2, widths=1:2)。您会看到第一个图的 y 轴相对于下面的图偏移了。
  • ggplot2 对象的大小还是一样的,只是绘图区域变小了。你可以尝试一些事情: 1. 旋转你的标签。 2. 移动你的标签。 3. 将你的标签分成他们自己的 grob。可能还有其他选择,但没有一个是“自动的”。
  • 这不能修复轴大小问题。
【解决方案2】:

根据我的评论(以及@Justin 答案中间的评论)facet_wrap 可能是要走的路。它会生成如下图所示的内容。显然,您需要考虑颜色、图例以及因素的顺序,但您可以看到一般方法。代码如下图。

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

【讨论】:

  • 我认为 faceting 不能满足 user443854 的需求,因为他的 p1 和 p2 地块有不同的几何形状,并且可能是独立的 ys。
猜你喜欢
  • 1970-01-01
  • 2011-11-06
  • 1970-01-01
  • 1970-01-01
  • 2018-02-01
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 2015-02-27
相关资源
最近更新 更多