Search code examples
rpanellattice

plot the first point of each group of panel data in lattice xyplot


I'm trying to create a line plot using groups and panels that superposes a symbol on the first value of each group. This attempt plots the first point of the first group only and does nothing for the other two groups.

library(lattice)
foo <- data.frame(x=-100:100, y=sin(c(-100:100)*pi/4))
xyplot( y~x | y>0,  foo, groups=cut(x,3),
        panel = function(x, y, subscripts, ...) {
          panel.xyplot(x, y, subscripts=subscripts, type='l', ...)
          # almost but not quite:
          panel.superpose(x[1], y[1], subscripts=subscripts, cex=c(1,0), ...) 
        } )

General solutions would be appreciated, to allow plotting of specific points within each group and panel (e.g., first, middle, and endpoints).

enter image description here


Solution

  • (Thanks for this good lattice question.) You should use Subscripts because it is the mechanism for picking individual data points for panels : Here you want to pick the groups by panel: groups[subscripts]. Once you have the right grouping variables you can use it to split your data and pick the first element of each group:

        ## first points
        xx = tapply(x,groups[subscripts],'[',1) 
        yy = tapply(y,groups[subscripts],'[',1)
        ## end points
        xx = tapply(x,groups[subscripts],tail,1) 
        yy = tapply(y,groups[subscripts],tail,1)
    

    The you plot the point using panel.points (higher level than the basic panel.superpose).

    library(lattice)
    foo <- data.frame(x=-100:100, y=sin(c(-100:100)*pi/4))
    xyplot( y~x | y>0,  foo, groups=cut(x,3),
            panel = function(x, y, subscripts, groups,...) {
              panel.xyplot(x, y, subscripts=subscripts, type='l',groups=groups, ...)
              # Note the use `panel.points` and the grouping using groups[subscripts]
              panel.points(tapply(x,groups[subscripts],'[',1), 
                           tapply(y,groups[subscripts],'[',1), 
                           cex=2,pch=20, ...) 
            } )
    

    enter image description here

    In case you want to color points according the color groups, you should add a groups argument to panel.points. (I leave you this as an exercise)