如何在我用type ='s'绘制的线下填写

时间:2013-06-19 11:37:56

标签: r plot polygon

我想使用plot(X, type='s')在一个步骤功能线IN图下填充该区域我尝试polygon但没有成功。

set.seed(1);y = abs(rnorm(10))
plot(y,ylim=c(0,max(y)), type="p",pch=24)
lines(y, type='s')
abline(h=0)

假设我想在曲线下方以及y=0上方绘制灰色 enter image description here

2 个答案:

答案 0 :(得分:11)

x <- seq_along(y)
y2 <- rep(y, each=2)
y2 <- y2[-length(y2)]
x2 <- rep(x, each=2)[-1]
x3 <- c(min(x2), x2, max(x2))
y3 <- c(0, y2, 0)

# because polygon() is dumb and wants a pre-existing plot
plot(x, y, ylim=c(0, max(y)), type="n")

polygon(x3, y3, border=NA, col="grey")
lines(x2, y2)

答案 1 :(得分:1)

Lattice解决方案,这是一个很好的HongOoi解决方案的基础。

set.seed(1)
xx <- c(1:10)
yy <- abs(rnorm(10))

library(lattice)
xyplot(yy~xx,type='s',
       panel=function(x,y,...){
         panel.xyplot(x,y,...)
         y2 <- rep(y, each=2)
         y2 <- y2[-length(y2)]
         x2 <- rep(x, each=2)[-1]
         x3 <- c(min(x2), x2, max(x2))
         y3 <- c(0, y2, 0)
         panel.polygon(x3, y3,col=rgb(1, 0, 0,0.5), border=NA)

       })

enter image description here