2012-11-28 27 views
1

再一次遇到了一个复杂的ggplot。我想要使​​用facet网格在一个小区内绘制不同的小区类型。facet_grid中的不同Plottypes

我希望我可以使用下面的例子清楚表达我的观点: 我想生成一个类似于第一张图的图,但上面的图应该看起来像第二张图。 我已经找到了使用子集函数的技巧,但我不能将垂直线添加到只有一个绘图,更不用说两个或三个(或指定颜色)。

CODE:

a <- rnorm(100) 
b <- rnorm(100,8,1) 
c <- rep(c(0,1),50) 


dfr <- data.frame(a=a,b=b,c=c,d=seq(1:100)) 
dfr_melt <- melt(dfr,id.vars="d") 

#I want only two grids, not three 
ggplot(dfr_melt,aes(x=d,y=value)) + facet_grid(variable~.,scales="free")+ 
geom_line(subset=.(variable=="a")) + geom_line(subset=.(variable=="b")) 

#Upper plot should look like this 
ggplot(dfr,aes(x=d,y=a)) + geom_line() + geom_line(aes(y=c,color="c"))+ 
geom_hline(aes(yintercept=1),linetype="dashed")+ 
geom_hline(aes(yintercept=-2),linetype="dashed") 

Example1

Example2

+0

btw:谁能告诉我为什么我的问候总是被省略。它看起来像我是一个不友好的人,我不是! – rainer

+0

不鼓励添加问候语:http://meta.stackexchange.com/q/2950/161858 – Andrie

+0

请在您的代码中添加一些空格,以便阅读起来更加轻松。 “<-'和','周围缺少空格会让我的眼睛受伤。 – Andrie

回答

5

如果我正确理解你的问题,你只需要一个variabledfr,以使刻面的工作:

dfr$variable = "a" 
ggplot(subset(dfr_melt, variable=="a"),aes(x=d,y=value)) + 
    facet_grid(variable~.,scales="free")+ 
    geom_line(data=subset(dfr_melt,variable=="a")) + 
    geom_line(data=subset(dfr_melt, variable=="b")) + 
    geom_line(data=dfr, aes(y=c, colour=factor(c))) + 
    geom_hline(aes(yintercept=1),linetype="dashed")+ 
    geom_hline(aes(yintercept=-2),linetype="dashed") 

请注意,我的阴谋没有锯齿锯齿线,这是因为我变了:

#This is almost certainly not what you want 
    geom_line(data=dfr, aes(y=c, colour="c")) 

#I made c a factor since it only takes the values 0 or 1 
    geom_line(data=dfr, aes(y=c, colour=factor(c))) 
    ##Alternatively, you could have 
    geom_line(data=dfr, aes(y=c), colour="red") #or 
    geom_line(data=dfr, aes(y=c, colour=c)) #or 

enter image description here

1

据我所知,您可以使用facet.grid不能把多个情节类型在一个图()。你两个选择,就我所看到的,是

  • 把空的数据中的第一个面,所以线是“有”,但没有显示出来,或

  • 以多条曲线组合成一个使用视口。

我认为第二个方案是比较一般,所以这就是我所做的:

#name each of your plots 
p2 <- ggplot(subset(dfr_melt, variable=="a"),aes(x=d,y=value)) + facet_grid(variable~.,scales="free")+ 
    geom_line(subset=.(variable=="a")) + geom_line(subset=.(variable=="b")) 

#Upper plot should look like this 
p1 <- ggplot(dfr,aes(x=d,y=a)) + geom_line() + geom_line(aes(y=c,color="c"))+ 
    geom_hline(aes(yintercept=1),linetype="dashed")+ 
    geom_hline(aes(yintercept=-2),linetype="dashed") 

#From Wickham ggplot2, p154 
vplayout <- function(x,y) { 
    viewport(layout.pos.row=x, layout.pos.col=y) 
} 

require(grid) 
png("myplot.png", width = 600, height = 300) #or use a different device, e.g. quartz for onscreen display on a mac 
grid.newpage() 
pushViewport(viewport(layout=grid.layout(2, 1))) 
print(p1, vp=vplayout(1, 1)) 
print(p2, vp=vplayout(2, 1)) 
dev.off() 

enter image description here

您可能需要摆弄了一下,让他们排队分毫不差。关闭上方情节的面部表情,并将下方情节的图例移动到下方,应该可以做到。

+0

您使用哪个ggplot2版本?与0.9.2.1我有一个错误,由于。在子集表示法 – agstudy

+0

也0.9.2.1,当我重新运行它,我也得到一个错误。不知道发生了什么事 - 显然我做了一次情节。没时间现在解决问题。 –