Change annotations in time series plots in R

For now, I can change annotations using the general plot command, disabling axes and annotations and reusing them using the axis command, for example.

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 cannot do this with a time series object for example.

www <- ""  
Maine.month <- read.table(www, header = TRUE)  
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 build Maine.98

with comments like:

"Jan-98"   "Feb-98"   "Mar-98"   "Apr-98"   "May-98"  etc?



source to share

2 answers

You have found a ts

time series type that is suitable for ARIMA modeling and a series with a fixed "delta t", for example, monotonic or quarterly.

But R works well with dates in general. Try experimenting with storing data in data.frame

, but convert the x-axis data to any type Date


. plot()

will call an axis formatting function that knows about the time, and you will get better defaults that you can still override.

Better yet, use the zoo or xts packages , which give you extra control, as well as bells and whistles:

 > X <- data.frame(x=seq(Sys.Date()-11*31,Sys.Date(),by="1 months"),  
 > 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 objects ts

, you have simpler converters as.zoo()

and as.xts()

. The help page plot.zoo

has examples for custom timeline formatting.



Just to add to what Dirk said:

Once you are using the correct date type (Date or POSIXt), 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.





All Articles