Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

plot

r

lattice

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

like image 951
ckluss Avatar asked Jan 16 '15 12:01

ckluss


1 Answers

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

like image 195
Roland Avatar answered Oct 23 '22 10:10

Roland