After kind answer from Joshua on my previous post about this "issue" ( Issue with quantmod add_TA and chart_Series - lines and text disappear after next add_TA is called ) I have added some "extensions" to quantmod that enable drawing lines/segments and texts. When doing so I encountered a problem I can not resolve:
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...
Any ideas on how to do this in a way that vertical lines are visible only on second segment of the graph (in the add_TA part, second segment) highly appreciated.
I have also created other functions for adding text and line segments in the same way to avoid replot issues (issue explained in linked question) if only graphics primitives are used. If anybody is interested I can share.
Best, Samo