rlatticetrellis

Stacked lines with multiple factors using lattice and R


Most of R is getting your data into the proper format and I am struggling with creating a two panel lattice plot with two groups of three each. Ultimately I would like to show a series of simplified box-pots which just show a line from the Lower95 to the Upper95 and a point for the Center, for each Drug and Test and have two panels (Sen & Spec) that have six lines (and points in them).

My simplified data look like this

   df2 <- data.frame (
     Center = c(0.94, 0.97, 0.95, 0.97, 1,    0.94,         1,    0.99, 0.96, 0.98, 0.98, 0.99),
     Lower95 =c(0.91, 0.95, 0.93, 0.95, 0.98, 0.91,         0.98, 0.96, 0.92, 0.96, 0.95, 0.96),
     Upper95 =c(0.96, 0.98, 0.97, 0.98, 1,    0.96,         1,    1,    0.98, 0.99, 0.99, 1   ),
     Y     =  c(1,2,3,4,5,6,1,2,3,4,5,6),
     Drug=c("INH","INH","INH","RIF","RIF","RIF","INH","INH","INH","RIF","RIF","RIF"),
     Test=c("LPA","MODS","PSQ","LPA","MODS","PSQ","LPA","MODS","PSQ","LPA","MODS","PSQ"),
     Measure=c("Sen","Sen","Sen","Sen","Sen","Sen","Spec","Spec","Spec","Spec","Spec","Spec") 
     ) 

   attach(df2)
   xyplot(Y~Lower95+Upper95|Measure, df=df2, type="o")

So this outputs this image and there are a couple of problems - Original:

  1. I am using Y as a 'dummy' variable to try to get the two groups of three tests on the same panel but that did not seem to work as intended. The two groups of three tests are in each panel (but see #2)
  2. The plot connects the three points of the three tests (not the two points of Lower95 and Upper95)
  3. It is not clear to me how to get the Center as a point into the chart(s)

Here is something like what I desire (my hack in GIMP) - Desired Chart

I've tried unsuccessfully to reshape the data, and a few other things within xyplot (e.g. different factors/groups) but I cannot seem to get it to work the way I'd like it to be.

Thanks for your help !


Solution

  • What you are drawing is most similar to a lattice dotplot. Standard lattice isn't great for error bars but the Hmisc library adds that functionality into lattice functions nicely. So you could do

    library(lattice)
    library(Hmisc)
    Dotplot(Test~Cbind(Center,Lower95,Upper95)|Measure+Drug, df2)
    

    to get

    enter image description here

    if you want to go a step further you can also include latticeExtra to move the drug labels to the left

    library(latticeExtra)
    useOuterStrips(Dotplot(Test~Cbind(Center,Lower95,Upper95)|Measure+Drug, df2))
    

    which results in

    enter image description here