[R] Custom ticks on x axis when dates are involved
Monica Pisica
pisicandru at hotmail.com
Wed Nov 24 20:27:55 CET 2010
Hi,
I have a set of irregular time series and i want to produce a simple plot, with dates on x axis and attribute value of y axis. This is simple enough but my x axis is divided automatically by ticks every 5 years. I would like to have a tick every year at January 1st. I am not sure how i can do that - i end up with something very close to what i want, but it is clunky and not very correct. I know that my dates are somehow internally converted in an integer that represents the number of seconds passed since an origin (i suppose it is 1st of January 1900). I think it would be easier to show you my example what i've done. I would be very happy to find out the correct way of actually doing this.
d <- c("4/6/1984", "9/29/1984", "1/19/1985", "3/27/1986", "10/3/1987", "10/8/1987", "1/28/1988", "12/16/1989", "10/11/1991", "10/5/1992", "11/15/1995", "4/7/1996", "10/3/1997", "2/28/1998", "10/11/2000", "10/30/2001", "2/27/2002", "12/28/2002", "10/20/2003", "10/20/2003", "10/20/2003", "11/7/2004", "10/9/2005", "10/9/2005", "10/28/2006", "3/7/2007", "4/6/2007", "10/1/2008", "11/2/2008", "9/2/2009")
land <- c(3094.083, 3173.706, 3032.062, 3110.191, 3013.832, 3013.843, 3030.776, 3111.819, 3131.474, 3104.857, 2992.511, 3018.579, 2994.332, 2992.453, 3065.483, 3077.917, 3096.034, 3057.518, 3089.202, 3082.897, 3086.080, 3071.480, 3106.573, 3109.163, 3124.328, 3118.239, 3119.106, 3107.055, 3113.695, 3113.021)
#transform d in dates:
mdY.format <- "%m/%d/%Y"
d1 <- as.POSIXct(strptime(d, format = mdY.format))
#Do the simple plot, supress ticks
plot(d1, land, xlab="Date", ylab = "Sq. Km.", xaxt = "n")
#Now dealing with my ticks and labels - the ugly part:
s1 <- (31+29+31+6)*24*60*60 # to be subtracted from earliest date to get 1st of January
s2 <- (29+31+30+31)*24*60*60 # to be added to the latest date to get 1st of January 2010
# number of seconds in a year - but does not take into consideration the leap years
t <- 365*24*60*60
axis(1, at = seq((range(d1)[1]-s1), (range(d1)[2]+s2), t), las = 2, labels = paste(seq(1984, 2010, 1)))
abline(v= seq((range(d1)[1]-s1), (range(d1)[2]+s2), t), lty = 2, col = "darkgrey")
Now the graph looks very close to what i want, but i know that my ticks actually are not exactly at 01/01/yyyy as i would like, although i suppose my error is not that much in this instance. However i would really appreciate if i can get the ticks on my x axis how i want in a much more elegant way - if possible (and if not at least in the correct way).
Thanks, and Happy Thanksgiving for those who celebrate ;-)
Monica
More information about the R-help
mailing list