[R] Adding colored background area to a time series plot

Gabor Grothendieck ggrothendieck at gmail.com
Sun Aug 15 18:40:24 CEST 2010


On Sun, Aug 15, 2010 at 12:21 PM, James Toll <james at jtoll.com> wrote:
> Hi,
>
> I am trying to add a rectangular colored background area to a plot of a time series of relative price changes.  I believe that what I'm trying to do is very similar to the question and example given here:
>
> http://www.mail-archive.com/r-help@stat.math.ethz.ch/msg73948.html
> http://www.mayin.org/ajayshah/KB/R/html/g5.html
>
> My problem/difference is that my time series looks like so:
>
>> library(quantmod)
>> getSymbols("^GSPC", from="2008-01-01")
>> xtsPR <- diff(log(Ad(GSPC)))
>> head(xtsPR)
>                     GSPC.Adjusted
> 2008-01-02            NA
> 2008-01-03   0.000000000
> 2008-01-04  -0.024857950
> 2008-01-07   0.003218041
> 2008-01-08  -0.018522677
> 2008-01-09   0.013532064
>
> So my dates along the x-axis are in the format "2008-01-02" rather than "2008", as in the example.
>
> To keep things simple, I've simply been trying to plot the time series using the plot command:
>
> plot(xtsPR)
>
> and then adding either a polygon, or preferably, a rect:
>
> rect(2009-01-02, -0.10, 2009-12-31, 0.10, border = 0, col = "blue")
>
> But nothing is added to the plot when I try to add the rectangle, but I don't get an error message either.
>
> My question is how do I specify my x coordinates to draw the polygon or rect, given that my scale is of the form "2008-01-02" rather than simply "2008"?
>
> Additionally, do I have to use polygon, even if I'm trying to drawing a rectangle, as was the case in the examples linked above?
>
> I'd like to be able to use this with chartSeries, rather than plot, but I thought it would be easiest to figure it out using plot first.  Clearly that hasn't helped me.
>

Try this for several examples:

library(zoo)
example(xblocks)



More information about the R-help mailing list