Changing the time labels on a plot
This post shows how to change the time labels on an R plot. Start by generating some data randomly:
x <- ts(rnorm(121, mean=1.4), start=c(2000,1), frequency=12)
That will create a variable x
running monthly from 2000 through 2009. You can plot the series like this:
plot(x)
If you do that, you let R choose which dates to plot. You can do it your way be removing the x-axis and defining your own. The key is to realize that a time series plot in R is an xy-plot, where the x-axis is time. Here’s how you remove the x-axis:
plot(x, xaxt="n")
You need two things to put your own time labels on the graph:
- The dates you want labeled.
- The information you want to label those dates with.
You can get a vector holding the dates of x
like this:
xt <- time(x)
Let’s say you want to label every third time value. You can get those dates like this:
xt <- time(x)[seq(1, 121, by=3)]
Now add the x-axis to your plot:
plot(x, xaxt="n", xlab="")
axis(side=1, at=xt, labels=xt)
That labels every third date. You can turn the labels perpendicular like this:
axis(side=1, at=xt, labels=xt, las=2)
You could use different labels too. Here’s some magic:
m <- c("Jan", "Apr", "Jul", "Oct")
y <- 2000:2009
tmp <- expand.grid(m,y)
lab <- c(paste(tmp[,1], tmp[,2]), "Jan 2010")
axis(side=1, at=xt, labels=lab, las=2)