Plot the first point of each panel data group in a xyplot grid

I am trying to create a line graph using groups and panels that overlay a symbol on the first value of each group. This attempt displays the first point of the first group 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), ...) 
        } )

      

It would be helpful to consider general solutions so that you can display specific points within each group and panel (for example, the first, middle and end points).

enter image description here

+3


source to share


1 answer


(Thanks for the good question lattice

.) You must use the subscripts, because it is a mechanism for selecting individual data points for panels: here you will want to choose a panel groups

on the panel: groups[subscripts]

. Once you have the grouping variables you want, you can use it to split your data and select 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)

      

You plot a point with panel.points

(higher level than baseline 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

If you want to mark points by color groups, you must add the groups argument to panel.points

. (I leave you this as an exercise)

+5


source







All Articles