2

Trying to put error bars on a time series plot using plot.xts

> myTS[1:20]
           [,1]
2013-07-01   29
2013-07-03   24
2013-07-03   16
2013-07-03   16
2013-07-03   12
2013-07-03   12
2013-07-03   16
2013-07-03   21
2013-07-03   21
2013-07-03   16
2013-07-05   12
2013-07-05   12
2013-07-05   12
2013-07-05   12
2013-07-08   16
2013-07-08   23
2013-07-08   16
2013-07-08   12
2013-07-09   16
2013-07-09   12

I've aggregated this using myTSquarterly = apply.quarterly(myTS,mean)

> myTSquarterly 
               [,1]
2013-09-30 24.50829
2013-12-31 23.79624
2014-03-31 24.15170
2014-06-30 24.57641
2014-09-30 23.71467
2014-12-31 22.99500
2015-03-31 24.50423
2015-06-30 25.19950
2015-09-30 24.76330
2015-12-31 24.65810
2016-03-31 25.35616
2016-06-30 22.71066
2016-07-27 20.63636

I can plot easily using plot.xts(myTSquarterly):

enter image description here

I can calculate standard deviation easily as well with apply.quarterly(myTS,sd)

I would like to add these standard deviation info as error bars to the plot, but I cannot find a method for this?

ollama
  • 157
  • 2
  • 5

1 Answers1

2

If you're going to use plotting using xts, you might want to consider using the development version of xts which is at v0.10 (CRAN version is still lower I think), where plotting capabilities for plot.xts have been improved. . Then check for simple examples ?plot.xts.

What you want to do could be done as follows:

# Want xts v0.10.0
library(devtools)
install_github("joshuaulrich/xts")


library(quantmod)
getSymbols("GOOG")
myTS <- GOOG[, 4]
myTSquarterly_mean <- apply.quarterly(myTS,mean)
myTSquarterly_sd <- apply.quarterly(myTS, sd)
c <- 2
plot(myTSquarterly_mean)
lines(myTSquarterly_mean - c * myTSquarterly_sd, col = "red")
lines(myTSquarterly_mean + c * myTSquarterly_sd, col = "red", pch = 17)
points(myTSquarterly_mean + c * myTSquarterly_sd, col = "red", pch = 17)

enter image description here

(If you want to keep using the older xts library to plot multiple curves on one plot, consider converting the time series to zoo type (as.zoo), then plot)

FXQuantTrader
  • 6,821
  • 3
  • 36
  • 67