在我之前关于这个“问题”(Issue with quantmod add_TA and chart_Series - lines and text disappear after next add_TA is called)的帖子中,约书亚的答复后,我在quantmod中添加了一些“扩展”,可以绘制线条/段和文本。这样做时我遇到了一个无法解决的问题:
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...
有关如何以垂直线仅在图形的第二段(在add_TA部分,第二段中)可见的方式执行此操作的任何想法都受到高度赞赏。
如果仅使用图形基元,我还以相同的方式创建了用于添加文本和线段的其他函数,以避免重新出现问题(链接问题中解释的问题)。如果有人有兴趣我可以分享。
最佳, 萨莫