Search code examples
rfinancequantmod

Override y-scale and x-scale using xlim/ylim or xrange/yrange in quantmod::chart_Series() - impossible?


I am trying to plot some support/resistance lines on top of quantmod::chart_Series(). The issue is that the interesting support/resistance lines are outside (below or above) series data range up to current time (I would also like to extend a chart a bit to the right beyond last timestamp of data).

Looking at the source code of quantmod::chart_Series() I can see no way of specifying ylim/xlim or, what was possible in "the old days" with quantmod::chartSeries using yrange to override y-scale. Comment here https://r-forge.r-project.org/scm/viewvc.php?view=rev&root=quantmod&revision=520 is also comfirming my hunch...

Is my diagnosis correct or is there maybe a way that enables y-scale overriding in quantmod::chart_Series? Any idea how to do what I want highly appreciated.

Thanks.

Best, Samo


Solution

  • The help page for chart_Series() notes -- three times! -- that it is experimental, so presumably the eventual polished version will have nice handles for setting these limits.

    Until then, here is a hack(?) that will let you set the limits and may teach you something about how chart_Series() works (i.e. by creating an environment/closure of class "replot", which stores all of the info needed to create a chart plot).

    ## Create an example plot
    getSymbols("YHOO")
    myChob <- chart_Series(YHOO)
    
    ## Plot it, with its default xlim and ylim settings
    myChob
    
    
    ## Get current xlim and ylim settings for `myChob` (chob = chart object)
    myxlim <- myChob$get_xlim()
    myylim <- myChob$get_ylim()
    
    ## Alter those limits
    myxlim <- c(1, 2000)
    myylim[[2]] <- structure(c(0, 50), fixed=TRUE)
    
    ## Use the setter functions in the myChob environment to set the new limits.
    ## (Try `myChob$set_ylim` and `ls(myChob$Env)` to see how/where these are set.)
    myChob$set_ylim(myylim)
    myChob$set_xlim(myxlim)
    
    ## Plot the revised graph
    myChob