Search code examples
rpanellattice

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


This is similar to a previous post, but it is still making me scratch my head.

For each group, and for each panel, I would like to identify and plot the maximum y-value point over the original xy line plot. There may be a way to do this using tapply, but I haven't been able to find it. Here's my attempt and where I get stuck:

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, groups, subscripts, ...) {
      panel.xyplot(x, y, subscripts=subscripts, type='l',groups=groups, ...)

      # get the index of the maximum y-value for each group
      max_ind <- tapply(y, groups[subscripts], function(x) { which(x==min(x))[1]} ) 

      # splits the data into groups
      x_g <- tapply(x, groups[subscripts], function(x){x})
      y_g <- tapply(y, groups[subscripts], function(x){x})

      # something goes here to extract the x- and y- values corresponding 
      # to the maximum index of each group
      #x_max = ??? 
      #y_max = ???

      panel.points(x_max, y_max, cex=2, pch=16,...)
    } )

Solution

  • Here's one way to go about it, using panel.superpose and panel.groups:

    xyplot(y ~ x | y > 0, foo, groups=cut(x, 3),
           panel = function(x, y, ...) {
             panel.superpose(x, y, pch=20, cex=1.5, ...,
                             panel.groups = function(x, y, col.symbol, ...) {
                               panel.lines(x, y, col=col.symbol)
                               panel.points(x[which.max(y)], max(y), 
                                            col.symbol=col.symbol, ...)
                             }
             )
           }
    )
    

    enter image description here