How to create a faceted line-graph using ggplot?

neversaint picture neversaint · Feb 1, 2013 · Viewed 13k times · Source

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:

enter image description here

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?

Answer

kohske picture kohske · Feb 1, 2013

Try this:

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

enter image description here