xyplot时间序列,正值为绿色,负值为红色,R

时间:2016-03-04 19:58:43

标签: r plot lattice

使用lattice::xyplot,是否有一种简洁的方法可以为下面的(简化)时间序列图中的红色和其他绿色的负值着色?

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

enter image description here

4 个答案:

答案 0 :(得分:7)

莱迪思基于grid,因此您可以使用网格剪辑功能

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

答案 1 :(得分:4)

当使用type =“l”时,你只有一个“线”,它只是一种颜色,所以你可能会选择颜色点:

set.seed(0); require(zoo); require(lattice)
vals <- zoo(cumsum(rnorm(100)))
png()
xyplot(vals, type=c("l","p"), col=c("red", "green")[1+( vals>0)], grid=T)
dev.off()

enter image description here

我通过Sundar Dorai-Rag, a fellow now at Google,找到了类似请求的解决方案(为上面和下面0的封闭区域着色,为此他获取X的交叉值的方法是反转{{1的结果}})如下所示:http://r.789695.n4.nabble.com/shading-under-the-lines-in-a-lattice-xyplot-td793875.html。我没有给封闭区域着色,而是给多边形的边框赋予了所需的颜色,并使内部“透明”:

approx

enter image description here

答案 2 :(得分:3)

我尝试为此编写一个自定义面板函数,它将在给定值上打破一行

panel.breakline <- function(x,y,breakat=0,col.line,upper.col="red",lower.col="green",...){
    f <- approxfun(x,y)
    ff <- function(x) f(x)-breakat
    psign <- sign(y-breakat)
    breaks <- which(diff(psign) != 0)
    interp <- sapply(breaks, function(i) uniroot(ff,c(x[i], x[i+1]))$root)
    starts <- c(1,breaks+1)
    ends <- c(breaks, length(x))

    Map(function(start,end,left,right) {
        x <- x[start:end]
        y <- y[start:end]
        col <- ifelse(y[1]>breakat,upper.col,lower.col)
        panel.xyplot(c(left, x, right) ,c(breakat,y,breakat), col.line=col,...)
    }, starts, ends, c(NA,interp), c(interp,NA))
}

您可以使用

运行
library(zoo)
library(lattice)
set.seed(0)
zz<-zoo(cumsum(rnorm(100)))

xyplot(zz, grid=T, panel.groups=panel.breakline)

enter image description here

你也可以改变断点或颜色

xyplot(zz, grid=T, panel.groups=panel.breakline, 
    breakat=2, upper.col="blue", lower.col="orange")

enter image description here

答案 3 :(得分:2)

如果一个人没有积分,那么我会坚持绘图(而不是格子)并使用剪辑,就像在这里的答案之一: Plot a line chart with conditional colors depending on values

dat<- zoo(cumsum(rnorm(100)))

plot(dat, col="red")

clip(0,length(dat),0,max(dat) )
lines(dat, col="green")