Search code examples
legendlattice

Can I use Lattice auto.key or key to make a legend with points for some data and lines for others?


I often make figures that have observed data represented as points and model-predicted data represented as lines, using distribute.type to assign graph types. Is there a way to make a legend that only shows points for the points data, and lines for the lines data? The auto.key default is points, and if I add lines with "list(lines=TRUE)" the legend shows both points and lines for every data label:

x <- seq(0, 8*pi, by=pi/6)

Y1pred <- sin(x)
Y1obs <- Y1pred + rnorm(length(x), mean=0, sd=0.2)
Y2pred <- cos(x)
Y2obs <- Y2pred + rnorm(length(x), mean=0, sd=0.4)
 
xyplot(Y1obs + Y2obs + Y1pred + Y2pred ~ x, 
        type=c('p','p','l','l'), 
        distribute.type=TRUE,
        auto.key=list(lines=TRUE, columns=2)
        )

There is a rather complicated example using 'key' on p. 158 of Deepayans' book on Lattice, I am wondering if there are simple options? enter image description here


Solution

  • Yes, following S, the lines components of key supports different type-s (but not points). Using auto.key, you could do

    xyplot(Y1obs + Y2obs + Y1pred + Y2pred ~ x, 
           type=c('p','p','l','l'), 
           distribute.type=TRUE,
           auto.key = list(points = FALSE, lines = TRUE,
                           columns = 2,
                           type = c('p','p','l','l')))
    

    Ideally, you would want to put the type only inside the lines component, and that's how you should do it if you use key. For auto.key, there can be only one line anyway, so this should be fine.