Search code examples
rquantmod

ploting multiple objects from a function in R


i'm trying to a function to chart a quantmod chart and some rect's on top. it's working fine when running from the cmd but when wrapping inside a function either only the rect are showing , or only the graph is showing, or sometimes neither is showing. Example code :

f1 <- function() { 
require(quantmod)
s <- get(getSymbols('PRGO'))["2012::"]
chart_Series(s)
u<-par("usr")
d<-data.frame(Buttom=c(100,90),Top=c(110,95))
rect(u[1],d[,'Buttom'],u[2],d[,'Top'],col=rgb(1,0,0,alpha=0.2),border=0)
}
  • you might need to run plot.new()
  • if you return the chart object from the function and print it, it works but i haven't found a way of returning both chart object and the rect's (the rect are a list as well)
  • i understand that functions work in a temporary environment - i haven't found a way of running the function in the global env. i don't know how to assign the rect to the chob in the global env.
  • the function will eventually do all the plotting - i want to add more lines, labels etc'.

Thanks.


Solution

  • If you wrap your chart_Series() inside a print it seems to work ?

    f1 <- function() { 
      require(quantmod)
      s <- get(getSymbols('PRGO'))["2012::"]
      print(chart_Series(s))
      u<-par("usr")
      d<-data.frame(Buttom=c(100,90),Top=c(110,95))
      rect(u[1],d[,'Buttom'],u[2],d[,'Top'],col=rgb(1,0,0,alpha=0.2),border=0)
    }
    
    f1()
    

    enter image description here