Search code examples
rplotlattice

lattice, connect points only if the connection has a positive slope


is there a comfortable way to connect points only if the connection has a positive slope? (otherwise the function should behave exactly as xyplot(...))

library(lattice)

dat <- data.frame(x=1:10,y=sample(1:10))

xyplot(y ~ x, data=dat,
       panel = function(x, y,...) { 
         panel.xyplot(x, y, type="o",...)
       }
)

so the result shoud be a plot like this, but without crossed lines:

enter image description here

Thank you Christof


Solution

  • dat <- dat[order(dat[, "x"]),]
    dat$group <- cumsum(c(1, diff(dat$y) < 0))
    
    
    xyplot(y ~ x, data = dat, groups = group,
           panel = function(x, y,...) { 
             panel.xyplot(x, y, type = "o", col = trellis.par.get("plot.line")$col, ...)
           }
    )
    

    resulting plot