简体   繁体   English

如何使用ggplot创建刻面线图?

[英]How to create a faceted line-graph using ggplot?

I have a data frame created with this code: 我有一个使用此代码创建的数据框:

require(reshape2)
foo <- data.frame( abs( cbind(rnorm(3),rnorm(3, mean=.8),rnorm(3, mean=.9),rnorm(3, mean=1))))
qux <- data.frame( abs( cbind(rnorm(3),rnorm(3, mean=.3),rnorm(3, mean=.4),rnorm(1, mean=2))))
bar <- data.frame( abs( cbind(rnorm(3,mean=.4),rnorm(3, mean=.3),rnorm(3, mean=.9),rnorm(3, mean=1))))

colnames(foo) <- c("w","x","y","z")
colnames(qux) <- c("w","x","y","z")
colnames(bar) <- c("w","x","y","z")

rownames(foo) <- c("n","q","r")
rownames(qux) <- c("n","q","r")
rownames(bar) <- c("n","q","r")

foo <- cbind(ID=rownames(foo),foo)
bar <- cbind(ID=rownames(bar),qux)
qux <- cbind(ID=rownames(bar),qux)

foo$fn <- "foo"
qux$fn <- "qux"
bar$fn <- "bar"

alldf<-rbind(foo,qux,bar)
alldf.m <- melt(alldf)

What I want to do is to create a ggplot line curve in facet format, so it creates a graph like this: 我想要做的是以facet格式创建一个ggplot线条曲线,因此它会创建一个如下图形:

在此输入图像描述

The actual graph does not contain upward lines - this is just a sketch so that the line separation is clear. 实际图形不包含向上线 - 这只是一个草图,因此线条分离是清晰的。

My current code doesn't work: 我当前的代码不起作用:

    library(ggplot2)
    p <- ggplot(data=alldf.m, aes(x=variable)) + 
           geom_line(aes(colour=ID),alpha=0.4)
    p <- p + facet_wrap( ~ fn)
    p

What's the best way to do it? 最好的方法是什么?

Try this: 尝试这个:

ggplot(data=alldf.m, aes(x=variable, y = value, colour = ID, group = ID)) + 
  geom_line() + facet_wrap(~fn)

在此输入图像描述

Even it is a ggplot2 is required by the OP , but I think this example is suitable for lattice also: 即使它是OP所需的ggplot2,但我认为这个例子也适用于lattice

library(lattice)
xyplot(data=alldf.m, value~variable|fn, type ='b', groups = ID, auto.key = T)

在此输入图像描述

and using latticeExtra we can get something colse to ggplot2 solution: 并使用latticeExtra我们可以获得ggplot2解决方案的一些东西:

 p <-  xyplot(data=alldf.m, value~variable|fn, type ='b', groups = ID, auto.key = T)
 update(p , par.settings = ggplot2like())

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM