[R] Conditional formatting of POSIXct date axis labels to only print year at a change

Duncan Murdoch murdoch.duncan at gmail.com
Wed Feb 12 02:43:27 CET 2014


On 14-02-11 6:13 PM, Peter Lomas wrote:
> Hello,
>
> I'm creating graphs like the following:
>
> x <- seq(as.POSIXct("2012-01-01"), as.POSIXct("2013-01-01"), by = "days")
> y <- (1:length(x)*10 + cumsum(rnorm(n=length(x), mean=0, sd= 100)))
> plot(x,y, type = 'l', xaxt='n')
> axis.POSIXct(side=1,at=seq(min(x),  max(x), by="months"),  format = "%b
> \'%y", labels = TRUE)
>
> For aesthetic reasons, I would only like to print the year label (%y) on
> the x axis at the change points of the year.  In this example, there would
> be a "Jan '12" and "Jan '13" with the months in between omitting the year
> label.
>
> Any clues would be appreciated!

Instead of labels=TRUE, compute the strings for the labels you want, and 
use those.  For example,

  ticks <- seq(min(x),  max(x), by="months")
  full <- format(ticks, format="%b \'%y")
  short <- format(ticks, format="%b")
  labels <- ifelse (short == "Jan", full, short)
  axis.POSIXct(side=1,at=ticks, labels = labels)

Duncan Murdoch




More information about the R-help mailing list