我再次面对一个复杂的ggplot.我想使用构面网格在一个图中绘制不同的绘图类型.
我希望我可以使用下面的例子清楚地说明我的观点:我想制作一个类似于第一张图片的图,但上图应该看起来像第二张图.我已经使用子集函数找到了这个技巧,但是我不能将垂直线添加到一个图中,更不用说两个或三个(或指定颜色).
码:
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")
Run Code Online (Sandbox Code Playgroud)


如果我正确理解您的问题,您只需要一个variable列dfr,以便让分面工作:
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")
Run Code Online (Sandbox Code Playgroud)
请注意,我的情节没有zig-zig线,这是因为我改变了:
#This is almost certainly not what you want
geom_line(data=dfr, aes(y=c, colour="c"))
Run Code Online (Sandbox Code Playgroud)
至
#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
Run Code Online (Sandbox Code Playgroud)
