Search code examples
rplotaxes

R plot - No control over number of items on x-axis


I am trying to draw a plot with all of the x-values shown on the x-axis.

m <- lm(MOCtfd_duration ~ CallMonth)
n <- lm(MTCtfd_duration ~ CallMonth)
summary(m)
summary(n)
title = OpName[1]
plot(MOCtfd_duration ~ CallMonth,type="l", col="red", ylim = c(600,1700),    ylab="Duration", las=2, main = title ) 
lines(MTCtfd_duration ~ CallMonth, col="blue")
axTicks(CallMonth)
abline(m, col="darkred")
abline(n, col="darkblue")

The values for the x-axis items are:

> CallMonth
 [1] "2014-05-01" "2014-04-01" "2014-03-01" "2014-02-01" "2014-01-01" "2013-12-01" "2013-    11-01" "2013-10-01" "2013-09-01" "2013-08-01"
[11] "2013-07-01" "2013-06-01" "2013-05-01" "2013-04-01" "2013-03-01" "2013-02-01" "2013-01-01" "2012-12-01" "2012-11-01" "2012-10-01"
[21] "2012-09-01" "2012-08-01" "2012-07-01" "2012-06-01"

But I am only getting two values: 2013 and 2014 even though all the points are being correctly reflected in the plot; this in itself is puzzling since these are not values in the data.

I have tried both using and not using axTicks() (for which the documentation seems very limited), but this doesn't appear to have any effect.

Can someone kindly point out my elementary error!


Solution

  • OK, finally sorted it in large part thanks to http://lukemiller.org/index.php/2014/01/make-your-r-figures-legible-in-powerpointkeynote-presentations/

    1. Suppress the standard x-axis in plot() using xaxt="n"

    2. Use axis.Date to select the side, and use prettyto determine the number of points, the frequency

    3. Use format "%m-%Y for the format of the axis

    4. Use las=2 to turn the new axis items through 90 degrees:

      plot(MOCtfd_duration ~ CallMonth,type="l", col="red", ylim = c(0,max(MOCtfd_duration)*1.3), xaxt="n", ylab="Duration", xlab="", main = title ) lines(MTCtfd_duration ~ CallMonth, col="blue") abline(m, col="darkred") abline(n, col="darkblue") legend(min(CallMonth),max(MOCtfd_duration)*1.15, c("MOC", "MTC"), fill=c("red","blue") ) axis.Date(side = 1, at=pretty(CallMonth, min.n=6, by="month"), format = "%m-%Y", las=2)