How to create a faceted line-graph using ggplot?

元气小坏坏 提交于 2019-12-05 09:34:32

问题


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:

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?


回答1:


Try this:

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




回答2:


Even it is a ggplot2 is required by the OP , but I think this example is suitable for lattice also:

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:

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



来源:https://stackoverflow.com/questions/14640872/how-to-create-a-faceted-line-graph-using-ggplot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!