views:

472

answers:

2

While I can change annotations with the generic plot command turning off axes and annotations and specifying them again using the axis command e.g.

cars <- c(1, 3, 6, 4, 9)

plot(cars, type="o", col="blue", ylim=range(0, cars), axes=FALSE, ann=FALSE)
axis(1, at=1:5, lab=c("Mon","Tue","Wed","Thu","Fri"))

I cant do it with time series object e.g.

www <- "http://www.massey.ac.nz/~pscowper/ts/Maine.dat"
Maine.month <- read.table(www, header = TRUE)
attach(Maine.month)
Maine.month.ts <- ts(unemploy, start = c(1996, 1), freq = 12)
Maine.98 <- window(Maine.month.ts, start = c(1998,1), end = c(1998,11))

How can I plot Maine.98 with annotations looking like
"Jan-98" "Feb-98" "Mar-98" "Apr-98" "May-98" etc?

+2  A: 

You found the ts type for time series which is suitable for ARIMA-modeling and series with fixed 'delta t' such as monhtly or quarterly series.

But R is good at working with dates in general. Try experimenting with keeping your data in a data.frame, but convert your x-axis data to either type Date or POSIXt. The plot() will call an axis-formatting function that knows about time and you get better defaults which you can still override.

Better still is use of packages zoo or xts which give you additional control as well as bells and whistles:

 > X <- data.frame(x=seq(Sys.Date()-11*31,Sys.Date(),by="1 months"),  
                    y=cumsum(rnorm(12)))
 > plot(X)                   # plot as a data.frame with Date column
 > library(zoo)
 > plot(zoo(X[,-1], X[,1]))  # plot as a zoo object
 > library(xts)
 > plot(xts(X[,-1], X[,1]))  # plot as an xts object

Edit: I forgot that if your data is already a ts object, you have easier converters as.zoo() and as.xts(). And the plot.zoo help page has examples for custom formatting of the time axis.

Dirk Eddelbuettel
Thank you. I wasn't aware that "by" in "seq" accepts strings like "1 months". Where is that referenced in help? Apart from months, what other time intervals can be used?
gd047
In this case it is 'seq.Date' to which `seq` dispatches on `Date` class objects.
Dirk Eddelbuettel
+1  A: 

Just to add to what Dirk said:

Once you're using a proper date type (Date or POSIXt), then you can use the format() command to choose how you want it to look in your plot:

> format(seq(Sys.Date()-11*31,Sys.Date(),by="1 months"), "%b-%y")
 [1] "Oct-08" "Nov-08" "Dec-08" "Jan-09" "Feb-09" "Mar-09" "Apr-09" "May-09"
 [9] "Jun-09" "Jul-09" "Aug-09" "Sep-09"

Look at the help for strptime for more examples of formatting options.

?strptime
Shane