Search code examples
rplotlattice

xyplot time series with positive values in green, negative in red, in R


Is there a neat way to color negative values in red and others in green for a (simplified) time series plot below, using lattice::xyplot?

set.seed(0)
xyplot(zoo(cumsum(rnorm(100))), grid=T)

enter image description here


Solution

  • Lattice is based on grid so you can use grid's clipping functionality

    library(lattice)
    library(grid)
    
    set.seed(0)
    x <- zoo(cumsum(rnorm(100)))
    
    xyplot(x, grid=TRUE, panel = function(x, y, ...){
           panel.xyplot(x, y, col="red", ...) 
           grid.clip(y=unit(0,"native"),just=c("bottom"))
           panel.xyplot(x, y, col="green", ...) })
    

    lattice with clipping