rggplot2latticetrellis

How to plot two lines by factor in a trellis graph?


Define:

df <- data.frame(
        line1 = rep(seq(1,5,by=1),2), 
        line2 = rep(seq(2,6,by=1),2),
        index = rep(seq(1,5,by=1),2),
        factor=rep(c("a","b"),each=5))

where line1 and line2 are two variables, say height and weight.

This is the simple style I would want for each panel (I would also like to change size of point markers, but not use how):

plot(df$line1[df$factor=="a"], type = "o", ylim=c(0,6))
lines(df$line2[df$factor=="a"], type = "o", lty=2, pch=0)

When I try this:

library(lattice)
xyplot(c(line1,line2)~index|factor,data=df,type="o")

the program treats all points as if they belong on one line.

In addition I am not sure how to feed in the arguments for plot style to get the desired results.

PS1. Surprisingly I have Googled around and found lots of scatter plots (with linear fits, densities, etc.) and histogram examples of trellis graphs, but not one of the simple thing I am trying to do.

PS2. I would like to tag this question trellis but do not have reputation points to create tag. Any volunteers?


Solution

  • The answer is actually very simple. Instead of combining line1 and line2 to a vector, just use the extended formula interface of xyplot :

    xyplot(line1+line2~index|factor,data=df,type="o")
    

    gives :

    enter image description here

    Check also ?xyplot read through the heaps of text and play a bit with the examples there. You'll find out how to customize this with titles, legends and the likes.

    As you labeled ggplot2 as well, this is one possibility of getting it done with that package :

    require(ggplot2)
    require(reshape)
    df2 <- melt(df,id=c("index","factor"))
    
    qplot(index,value,variable,facets = .~factor ,
              data=df2,geom="line",colour=variable)
    

    Gives :

    enter image description here