[R] plotting dates, incorrectly scaled x-axis?

Ted Harding Ted.Harding at wlandres.net
Sun Feb 12 12:15:46 CET 2012


On 12-Feb-2012 Christof Kluß wrote:
> Hi,
> 
> I want to plot with axis.Date(), but something is scaled incorrectly.
> The red vertical line in is put on a totally wrong position.
> (sample below)
> 
> Do you have an idea what I'm doing wrong?
> 
> Thx
> Christof
> 
> 
> x11(width=30, height=20)
> 
> x<-seq(as.Date("2010-02-27"), as.Date("2011-03-28"),"month")
> y <- seq(0,100,length=length(x))
> 
> plot(y ~ x, type="o", tck=1, xaxt="n")
> 
> axis.Date(1, at=x, labels=format(x,"%b\n%Y"), padj=0.5)
> 
> abline(v=as.Date("2011-01-01"), col="red", lty="dashed")

I don't think it is in the wrong position! What is happening
is that your month labels on the X-axis are not at the dates
one would intuitively expect.

  x
  #  [1] "2010-02-27" "2010-03-27" "2010-04-27" "2010-05-27"
  #  [5] "2010-06-27" "2010-07-27" "2010-08-27" "2010-09-27"
  #  [9] "2010-10-27" "2010-11-27" "2010-12-27" "2011-01-27"
  # [13] "2011-02-27" "2011-03-27"

so the labels "Feb 2010", "Mar 2010",  etc., are placed on
tick-marks which occur on the 27th day of each month.

Your abline() is dated "2011-01-01", which is five days
after "2010-12-27" = x[11], fourth from the end.

If you look at the plot, you will see that the read line
is a little bit to the right of the fourth tick from the
end "Dec 2010", which is just where it should be, given
that you have placed the month names at the 27th of each month.

One solution would be to use

  x<-seq(as.Date("2010-02-01"), as.Date("2011-03-01"),"month")

which would place these on the first of each month. But you
may have other reasons for wanting to choose the 27th, in which
case life may get a little more complicated!

Hopiung this helps,
Ted.

-------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at wlandres.net>
Date: 12-Feb-2012  Time: 11:15:43
This message was sent by XFMail



More information about the R-help mailing list