use*_*440 6 r ggplot2 xts quantmod
我正在使用一些时间序列数据,并希望在某些条件成立时突出显示图表区域.例如:
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))
Run Code Online (Sandbox Code Playgroud)
上面的代码绘制了数据,但是如何在高于sma的情况下突出显示该部分?这个问题类似于如何突出情节的时间范围?,但那是手动的.ggplot2中是否有一个用于条件绘图的函数?
GSe*_*See 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)
Run Code Online (Sandbox Code Playgroud)
将其与您所链接问题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)
Run Code Online (Sandbox Code Playgroud)
你得到:

如果颠倒绘制的顺序和使用alpha=1中geom_rect它可能(也可能不会)看起来更像你的愿望:
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))
Run Code Online (Sandbox Code Playgroud)

既然你有一个xts对象.您甚至可能不想转换为data.frame.以下是如何使用Michael Weylandt创建plot.xts的xtsExtra包中的全新方法绘制它,作为Google Summer of Code 项目的一部分.
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)
Run Code Online (Sandbox Code Playgroud)
