2014-04-14 20 views
0

這項研究樣本與我所需要的非常接近。問題是,如何獲得如下圖所示的條件背景色。這個圖表有兩個類別,我有三個,所以我會用第三個紋理。如何在R中實現這樣的圖形

隨時間變化的條件類別位於名稱爲CL,C和CR的向量中。

sample graph

下面是一些樣本數據。所以有索引,然後是政府類型(中間偏左,居中偏右)。在數據中有72個政府條款,所以有72個連續的運行,因此,至少用手工來完成這個操作是非常麻煩的。我明白,首先我需要繪製類別,然後將這一行添加到情節,我會在事後關注座標軸並最後添加它們。

shareindex categ 
100   C 
103   C 
104   C 
102   CL 
99   CL 
98   CR 
99   CR 
101   CL 
104   CL 
105   CR 
104   CR 
102   C 
103   C 
+3

能否請您提供的樣本數據集,所以我們不必生成樣本*和*你的解決方案?此外,您嘗試了什麼,圖表的哪一部分對您來說很難? – Jealie

+1

您可以使用'rect'作爲灰色區域。 –

+0

要理解縮放數據和繪製第二個數據集(即波動率和價格)背後的想法,它可能會幫助您在此處閱讀我的答案:[在2 y座標軸上繪製同一圖形上的多個數據集](http:// stackoverflow.com/a/18875822/1217536)。 – gung

回答

0

您可以使用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

編輯爲您的數據:

## 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

乾杯,

亞歷

+0

你是對的,我添加了結果圖 – alko989

+0

謝謝,花了一些時間弄清楚,但這有助於。 – Roope

2

下面是一些示例數據,並使用panel.first參數繪製矩形來plot通話。我在這裏建議使用lapply調用來繪製許多矩形。

# data 
set.seed(1) 
x <- rnorm(1000) 
x2 <- cumsum(x) 
y <- rnorm(1000) 
y2 <- cumsum(y)-5 
ranges <- list(c(5,10), c(20,100), c(200,250), c(500,600), c(800,820), c(915,930)) 

# expression to be used for plotting gray boxes 
boxes <- expression(lapply(ranges, function(z) rect(z[1],-100,z[2],100, col='gray', border=NA))) 

# the actual plotting 
plot(1:1000, x2, type='l', xlab='time', panel.first = eval(boxes)) 
lines(1:1000, y2, col='red') 

enter image description here

相關問題