Reputation: 1726
When drawing axis for time series, we usually create the tick marks and add the axis separately. Since I have to plot many time series, I tried to write the following function :
Simple plot command
set.seed(1)
x <- as.ts(rnorm(1:150))
plot <- plot(x, xaxt = "n", yaxt = "n")
Convert a set of commands from this answer into a function
tt = seq(as.Date("1994-03-01"), by="months", length=150)
tsAxis <- function (tt) {
ix <- seq_along(tt) # number of ticks
fmt <- "%b-%y" # format of time
labs <- format(tt, fmt) # names or labels of dates
axis(1, at = tt[ix], labels = labs[ix],
tcl = -0.7, cex.axis = 0.7, las = 2)
}
Then tsAxis(tt) must draw the axis but it doesnot and there is no error either. Even typing the commands separately does not plot the axis.
Any solutions?
Upvotes: 1
Views: 843
Reputation: 8717
It seems that R represents the x-axis with integers in this case (i.e. x=1 is the first event, x=2 is the second event, etc.). You can see this if you run the code:
set.seed(1)
x <- as.ts(rnorm(1:150))
# Take a look at the x-axis
plot <- plot(x)
We can modify your code to reflect this:
tt = seq(as.Date("1994-03-01"), by="months", length=150)
tsAxis <- function (tt) {
ix <- seq_along(tt) # number of ticks
fmt <- "%b-%y" # format of time
labs <- format(tt, fmt) # names or labels of dates
# Change "at=tt[ix]" to "at=ix" here!
axis(1, at = ix, labels = labs[ix],
tcl = -0.7, cex.axis = 0.7, las = 2)
}
Or if you want to plot every third tick mark, just change ix <- seq_along(tt)
to ix <- seq(1, length(tt), 3)
and it should work.
Upvotes: 1