您可以使用rect
,使矩形和情節線索重要的是
爲您的數據例如頂部:
set.seed(1)
x <- 1:100
y <- cumsum(rnorm(100))
z <- c(rep(1, 10), rep(2,20), rep(1,40), rep(3,30))
plot(x, y, type="n")
rect(xleft = x - 1, xright = x, ybottom=par("usr")[3], ytop=par("usr")[4], col=z, border=NA)
lines(x, y, col="white")
![Example plot](https://i.stack.imgur.com/pfwkQ.png)
編輯爲您的數據:
## Data frame with the data
dat <- data.frame(shareindex=c(100,103,104,102, 99,98,99,101,104,105,104,102,103),
categ=c("C","C","C","CL","CL","CR","CR", "CL", "CL","CR", "CR","C", "C"))
## Add index column
dat$id <- seq(along.with=dat$shareindex)
# Add your background colors here
cols <- c("lightgray","grey", "lightblue")
## Just an empty plot
plot(dat$id, dat$shareindex, type="n", ylab="Share index", xlab="id")
## Plot the rectangles for the background
rect(xleft =dat$id - 1 , xright = dat$id,
ybottom=par("usr")[3], ytop=par("usr")[4],
col=cols[dat$categ], border=NA)
## Plot the line
lines(dat$id, dat$shareindex, lwd=2)
輸出看起來是這樣的:
![Plot of your data](https://i.stack.imgur.com/DdanG.png)
乾杯,
亞歷
能否請您提供的樣本數據集,所以我們不必生成樣本*和*你的解決方案?此外,您嘗試了什麼,圖表的哪一部分對您來說很難? – Jealie
您可以使用'rect'作爲灰色區域。 –
要理解縮放數據和繪製第二個數據集(即波動率和價格)背後的想法,它可能會幫助您在此處閱讀我的答案:[在2 y座標軸上繪製同一圖形上的多個數據集](http:// stackoverflow.com/a/18875822/1217536)。 – gung