use*_*854 7 r ggplot2 gridextra
可能重复:
左对齐两个图形边(ggplot)
我试图ggplot在同一页面上,顶部和底部放置两个图,以便它们的宽度相同.数据来自相同的时间序列,x轴是时间,因此重要的是具有相同时间的数据点不会相对于彼此水平移位.我尝试grid.arrange从包gridExtra:
grid.arrange(p1, p2)
Run Code Online (Sandbox Code Playgroud)
但由于y轴标签的宽度不同,图表的宽度不同.我查看了这篇涉及类似问题的帖子,但我无法应用这些信息来解决我的问题.

Jus*_*tin 11
帮助文字grid.arrange说:
Arguments:
...: plots of class ggplot2, trellis, or grobs, and valid
arguments to grid.layout
Run Code Online (Sandbox Code Playgroud)
所以阅读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.
Run Code Online (Sandbox Code Playgroud)
换句话说,您可以将宽度和高度作为向量传递. 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)
Run Code Online (Sandbox Code Playgroud)
还值得一提的是,类似的效果可以用经常来完成melt从reshape2封装,facet_wrap或facet_grid在ggplot2.
根据我的评论(以及@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")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21487 次 |
| 最近记录: |