1

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?

Community
  • 1
  • 1
Anusha
  • 1,716
  • 2
  • 23
  • 27
  • In your `axis` function, try changing the parameter `at=tt[ix]` to `at=ix`. It seems R does not have the x-axis as dates form, but as integers. – ialm Jun 17 '13 at 20:58
  • Thanks. The axis are plotted now but raises another question. If we want only a third of the tick marks, `ix <- seq(1, length(tt), 3)`, then number of ticks and labels dont match.How to specify tick locations in that case? – Anusha Jun 17 '13 at 21:17
  • Have you tried changing the line `ix <- seq_along(tt)` to `ix <- seq(1, length(tt), 3)` and running your code again? Seems to work for me. I have `axis(1, at = ix, labels = labs[ix], tcl = -0.7, cex.axis = 0.7, las = 2)` in the `tsAxis` function, which seems to work. – ialm Jun 17 '13 at 21:38
  • I tried that but it was giving error that at and label lengths differ. Its working now. – Anusha Jun 17 '13 at 21:48
  • Would you like to post the comment as an answer or is this question trivial and to be deleted ? – Anusha Jun 17 '13 at 21:50
  • I added my comments as an answer. Glad I could help! – ialm Jun 17 '13 at 21:56

1 Answers1

1

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.

ialm
  • 8,510
  • 4
  • 36
  • 48