Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a faceted line-graph using ggplot?

Tags:

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?

like image 274
neversaint Avatar asked Feb 01 '13 06:02

neversaint


People also ask

What is faceting in Ggplot?

Faceting is the process that split the chart window in several small parts (a grid), and display a similar chart in each section. Each section usually shows the same graph for a specific group of the dataset. The result is usually called small multiple.

What is a facet in R studio?

The facet approach partitions a plot into a matrix of panels. Each panel shows a different subset of the data. This R tutorial describes how to split a graph using ggplot2 package. There are two main functions for faceting : facet_grid()

What does facet wrap do in R?

facet_wrap() makes a long ribbon of panels (generated by any number of variables) and wraps it into 2d. This is useful if you have a single variable with many levels and want to arrange the plots in a more space efficient manner.


2 Answers

Try this:

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

enter image description here

like image 83
kohske Avatar answered Sep 20 '22 06:09

kohske


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) 

enter image description here

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()) 

enter image description here

like image 25
agstudy Avatar answered Sep 18 '22 06:09

agstudy