6

この「問題」( quantmod add_TA および chart_Series に関する問題 - 次の add_TA が呼び出されると線とテキストが消える)に関する私の以前の投稿でのジョシュアからの親切な回答の後、線/セグメントとテキストの描画を可能にするいくつかの「拡張機能」を 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...

垂直線がグラフの 2 番目のセグメント (add_TA 部分の 2 番目のセグメント) にのみ表示されるようにする方法についてのアイデアは高く評価されています。

グラフィックプリミティブのみが使用されている場合、再プロットの問題(リンクされた質問で説明されている問題)を回避するために、同じ方法でテキストと線分を追加するための他の関数も作成しました。誰かが興味を持っているなら、私は共有できます。

ベスト、サモ

4

0 に答える 0