R 向图表系列添加垂直线并添加图表
在约书亚对我上一篇关于这个“问题”的帖子做出善意的回答之后,我在quantmod中添加了一些“扩展”,可以绘制线条/线段和文本。执行此操作时,我遇到了无法解决的问题:R 向图表系列添加垂直线并添加图表,r,finance,quantmod,R,Finance,Quantmod,在约书亚对我上一篇关于这个“问题”的帖子做出善意的回答之后,我在quantmod中添加了一些“扩展”,可以绘制线条/线段和文本。执行此操作时,我遇到了无法解决的问题: require(quantmod) add_VerticalLine<-function(xCoordinatesOfLines, on=1, ...) { lenv <- new.env() lenv$add_verticalline <- function(x, xCoordinatesOf
require(quantmod)
add_VerticalLine<-function(xCoordinatesOfLines, on=1, ...) {
lenv <- new.env()
lenv$add_verticalline <- function(x, xCoordinatesOfLines, ...) {
xdata <- x$Env$xdata
xsubset <- x$Env$xsubset
xcoords <- seq(1:NROW(xdata[xsubset]))[index(xdata[xsubset]) %in% index(xCoordinatesOfLines[xsubset])]
abline(v=xcoords, ...)
}
mapply(function(name, value) {assign(name,value,envir=lenv)}, names(list(xCoordinatesOfLines=xCoordinatesOfLines, ...)), list(xCoordinatesOfLines=xCoordinatesOfLines, ...))
exp <- parse(text=gsub("list","add_verticalline", as.expression(substitute(list(x=current.chob(),
xCoordinatesOfLines=xCoordinatesOfLines, ...)))), srcfile=NULL)
plot_object <- current.chob()
lenv$xdata <- plot_object$Env$xdata
plot_object$set_frame(sign(on)*abs(on)+1L)
plot_object$add(exp,env=c(lenv, plot_object$Env),expr=TRUE)
plot_object
}
datesForLines <- c("2012-02-06", "2012-02-07")
verticalLines.xts <- xts(rep(0, length(datesForLines)), order.by=as.Date(datesForLines))
SPX <- getSymbols("^GSPC", from="2012-01-01", auto.assign=FALSE)
chart_Series(SPX, subset="2012")
add_VerticalLine(verticalLines.xts, on=1, col=c('red', 'blue'), lwd=2)
add_TA(SMA(SPX))
# Everything is fine up to this point, but, when you execute next line (adding vertical line also to second segment of the graph):
add_VerticalLine(verticalLines.xts, on=2, col=c('blue', 'red'), lwd=2)
# You can see that vertical lines are drawn below the SMA and not visible. There seems to be some layering mechanism I do not understand...
require(quantmod)
将x值乘以3即可。绘图系统似乎在烛台的两侧添加了索引。