Search code examples
rquantmod

R quantmod chart_Series: Title and Subtitle allignment


I am having problems with aligning my subtitle in chart_Series. At present it is just writing over the top of the x axis. Also is it possible to switch off the text that is automatically written at the top of a chart_Series chart so I can replace it with my own

  library(quantmod)
  getSymbols("SPY", from="2013-01-01", to=Sys.Date())
  chart_Series(SPY)


  title("S&P Index", sub = "text1\n\text2\ntext3",
  cex.main = 2,   font.main= 4, col.main= "blue",
  cex.sub = 0.75, font.sub = 3, col.sub = "red")

I would be grateful for your help.


Solution

  • The 'quantmod' graphics are object-oriented. Data is stored in an environment (named 'Env') inside another environment (named whatever you name it, 'cspy' in this case). Special charting functions are stored with along with the data in a 'proto'-object. It is a more object-oriented approach than is used in either the S3 or S4 programming paradigms that are much more common in R. The 'proto'-package should be consulted for more details. After nosing around the code in chartSeries and the object it creates, I can get the labeling at the top to go away with this:

    cspy <- chart_Series(SPY, name = NULL)
    cspy$Env$actions[[4]] <- NULL
    cspy
    

    The 'quantmod' code has this:

        cs$Env$name <- name
        text.exp <- c(expression(text(1 - 1/3, 0.5, name, font = 2, 
            col = "#444444", offset = 0, cex = 1.1, pos = 4)), 
                      expression(text(NROW(xdata[xsubset]), 
            0.5, paste(start(xdata[xsubset]), end(xdata[xsubset]), 
                sep = " / "), col = 1, adj = c(0, 0), pos = 2)))
        cs$add(text.exp, env = cs$Env, expr = TRUE)
    

    ... but I wasn't able to figure out a name for that leaf so I looked at :

    cspy$Env$actions
    

    ... and saw that the name and date-range were in the 4th item. so I just deleted it. (To get rid of only the name it is trivial: chart_Series(SPY, name = NULL). (I don't know if the location of that graphical item in the object will be consistent and I do not see a method for access that object-leaf, so this is possibly an unstable hack.)

    To make room for the margin text (subtitle):

     png("out.png")
     myoma <- par("oma")
     myoma[1] <- 3
     par("oma" =myoma)
     cspy
     title("S&P Index",  cex.main = 2,  font.main= 4, col.main= "blue")
       mtext(text= "text1\ntext2\ntext3", side=1, cex = 0.75, font = 3, col = "red",line=7)
     dev.off()
    

    enter image description here