# [R] Adding a polygon to a time series plot

Andy Bunn abunn at whrc.org
Fri Dec 10 20:01:20 CET 2004

```Preamble: Sorry for being dense.

Now that that's done, here are my questions.

I want to put a polygon on a plot of a time series. I'm going to add lines
from a smooth.spline interpolation and other annotation to it. But here's
the general idea:

# Start code
n <- 121
dat <- rnorm(n)
plot(dat, type="n")
polygon(c(1:n,n:1), c(dat,c(rep(0,n))), col = "gray80", border = NA)
# End code

What if dat is a time series?

# Start code that won't parse.
dat.ts <- ts(rnorm(n), start = 1980, frequency = 12)
plot(dat.ts, type="n")
polygon(...) # How do I specify x and y for the time series?
# Is it easier to skip the time series and add time as an
axis
# End code that won't parse

Here's a work around that is cumbersome.

# Start code
dat.ts <- ts(rnorm(n), start = 1980, frequency = 12)
dat <- as.vector(dat.ts)
plot(1:n, dat, type="n", xaxt = "n", axes = FALSE, xlab = "", ylab =
"")
polygon(c(1:n,n:1), c(dat,c(rep(0,n))), col = "gray80", border = NA)
axis(1, at = seq(1, n, by = 12), labels = c(1980:1990))
# End code

Can I use polygon with a time series object? Or is it too awkward?

Thanks, Andy

```