且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何控制gridExtra中的绘图宽度?

更新时间:2023-10-04 23:18:10

在@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&lt ; - 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)


Possible Duplicate:
left align two graph edges (ggplot)

I am trying to put two plots produced with ggplot on the same page, top and bottom, so that their widths are the same. The data is from the same time series, x axis being time, so it is important that data points with the same time are not shifted horizontally with respect to each other. I tried grid.arrange from package gridExtra:

grid.arrange(p1, p2)

but the plots have different widths due to different widths of y axis labels. I looked at this post that deals with similar problem, but I could not apply that information to solve my problem.

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