[R] Plot with x-axis dates

Duncan Murdoch murdoch at stats.uwo.ca
Sat Feb 7 12:10:12 CET 2009

On 06/02/2009 4:48 PM, Paul Warren Simonin wrote:
> Hello,
>    I am attempting to create plots using two continuous variables and  
> it seems I should be able to use the simple "plot" command. However,  
> my x-axis values are dates, and I believe this could be the reason I  
> am receiving error messages reading:
> Error in Summary.factor(c(2L, 4L, 3L, 5L, 6L, 7L, 1L), na.rm = FALSE) :
>    range not meaningful for factors
> I have attempted to convert the date values to official dates within R  
> and have done that successfully using the as.date function, but this  
> did not help in the plots. So, how can one create plots in which the  
> x-axis is date values? I know it would be possible to convert all my  
> dates into a different linear scale (e.g., julian dates). However, I  
> would like to complete this process as simply as possible.

You can do plots using dates on the axis, e.g.

dates <- ISOdate(2009, 1:12, 1) # first of every month
plot(dates, 1:12)

Now sometimes the default tick choices for dates don't look great, e.g.

plot(dates[1:3], 1:3)

only gets two ticks labelled Jan and Mar, but you can specify your own 
locations and labels:

plot(dates[1:3], 1:3, xaxt="n")
axis(1, at=dates[1:3], labels=format(dates[1:3], "%b %d"))

Duncan Murdoch

More information about the R-help mailing list