2012-08-26 85 views
6

我正在處理一些時間序列數據,並希望在特定條件成立時突出顯示圖表區域。例如:ggplot2:突出顯示圖表區域

require(ggplot2) 
require(quantmod) 
initDate <- "1993-01-31" 
endDate <- "2012-08-10" 
symbols <- c("SPY") 
getSymbols(symbols, from=initDate, to=endDate, index.class=c("POSIXt","POSIXct")) 
spy<-SPY$SPY.Adjusted 
spy$sma<-SMA(spy$SPY.Adjusted,200) 
spy<-spy[-(1:199),] 
spy<-as.data.frame(spy) 
ggplot(spy,aes(x=index(spy),y=spy$SPY.Adjusted))+geom_line()+geom_line(aes(x=index(spy),y=spy$sma)) 

上面的代碼繪製的數據,但我怎麼能突出部當過密切高於SMA?這個問題與How to highlight time ranges on a plot?類似,但後來是手動的。 ggplot2中是否有條件繪圖的函數?

+3

問題的谷歌暑期的一部分,你鏈接到_is_的方式做這個。 ** ggplot2 **還沒有功能來理解像'geom_shade_the_region_that_I_have_in_mind_you_know_that_one()'這樣的功能。你必須實際告訴它你想要遮蔽的區域。 – joran

+1

如果您將適當的庫調用指示需要哪些程序包來運行該代碼,那麼您將增加獲得非數量實驗代碼的機會。 –

+0

@joran非常感謝有見地的答案〜會努力想出有用的東西。 – user1234440

回答

13

根據quantmod包的TA.R文件中的代碼,這裏是使用rle來查找矩形的開始和結束的代碼。

runs <- rle(as.logical(spy[, 1] > spy[, 2])) 
l <- list(start=cumsum(runs$length)[which(runs$values)] - runs$length[which(runs$values)] + 1, 
      end=cumsum(runs$lengths)[which(runs$values)]) 
rect <- data.frame(xmin=l$start, xmax=l$end, ymin=-Inf, ymax=Inf) 

再加上從accepted answer的問題一些ggplot2代碼鏈接到您:

ggplot(spy,aes(x=index(spy),y=spy$SPY.Adjusted))+geom_line()+geom_line(aes(x=index(spy),y=spy$sma))+geom_rect(data=rect, aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax), color="grey20", alpha=0.5, inherit.aes = FALSE) 

,你會得到:

enter image description here

如果顛倒繪製的順序並在geom_rect中使用alpha=1它可能(或可能不)看起來更像你的願望:

ggplot(spy,aes(x=index(spy),y=spy$SPY.Adjusted))+geom_rect(data=rect, aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax), border=NA, color="grey20", alpha=1, inherit.aes = FALSE)+geom_line()+geom_line(aes(x=index(spy),y=spy$sma)) 

enter image description here


既然你有一個xts對象。你甚至可能不想轉換成data.frame。這裏是你如何能夠使用由邁克爾Weylandt創建xtsExtra包全新plot.xts方法繪製它的代碼project.

spy <- as.xts(spy) 
require(xtsExtra) 
plot(spy, screens=1, 
    blocks=list(start.time=paste(index(spy)[l$start]), 
       end.time=paste(index(spy)[l$end]), col='lightblue'),      
    legend.loc='bottomright', auto.legend=TRUE) 

enter image description here

+0

+1很熱。邁克爾確實做了一些很棒的工作 –

相關問題