Label X Axis in Time Series Plot using R

I am somewhat new to R and have limited experience with plotting in general. I have been able to work get my data as a time series object in R using zoo, but I am having a hard time having the xaxis be labeled correctly, if it all.

When I plot my zoo object

plot(z)

The x-axis only shows one label, the year 2010. when the series is weekly spanning from April 2009 to October 2010.

I tried to convert my series back to a ts object, and even a data frame (only one column and doesn't include the dates).

Simply, how can I control the x-axis labels generally, and with time series objects?

Thanks in advance!


Solution 1:

Start with an example:

x.Date <- as.Date(paste(rep(2003:2004, each = 12), rep(1:12, 2), 1, sep = "-"))
x <- zoo(rnorm(24), x.Date)
plot(x)

If we want different tick locations, we can suppress the default axis plotting and add our own:

plot(x, xaxt = "n")
axis(1, at = time(x), labels = FALSE)

Or combine them:

plot(x)
axis(1, at = time(x), labels = FALSE)

You need to specify the locations for the ticks, so if you wanted monthly, weekly, etc values (instead of observations times above), you will need to create the relevant locations (dates) yourself:

## weekly ticks
plot(x)
times <- time(x)
ticks <- seq(times[1], times[length(times)], by = "weeks")
axis(1, at = ticks, labels = FALSE, tcl = -0.3)

See ?axis.Date for more details, plus ?plot.zoo has plenty of examples of this sort of thing.

Solution 2:

The axis labeling doesn't line up with even monthly divsions but may be useful in some situations. Random data (summed) over last 500 days:

xx.Date <- as.Date((Sys.Date()-500):Sys.Date())
x <- zoo(cumsum(rnorm(501)), xx.Date)
tt=time(x)
plot(x, xaxt ="n")
tt <- time(x)
ix <- seq(1, length(tt), by=60) #every 60 days
fmt <- "%b-%d" # format for axis labels
labs <- format(tt[ix], fmt)
axis(side = 1, at = tt[ix], labels = labs,  cex.axis = 0.7)

enter image description here