[R] Line Plot with Dates on X-axis

mah harwood262 at gmail.com
Wed Jan 20 18:41:58 CET 2010


I am trying to generate a line graph with quarterly time buckets (with
nice labels) on the x-axis.  The first block of code below will
generate the graph with nicely formatted x-axis labels, but the
"type=" and "col=" options are not recognized when factors are used
for the x-axis.

The second block, where the quarter values are mapped into dates, will
plot the line nicely but the x-axis is the number of days since
1/1/1970.  How do I either get the first block to recognize the
desired format, or the second block to format the x-axis as quarters?

Thank you in advance!

#block 1
time.val <- as.factor(c
("2004Q1","2004Q2","2004Q3","2004Q4","2005Q1","2005Q2"))
inc <- c(0.9903797, 1.3741467, 0.9938702, 0.4252443, 0.7700158,
1.1770313)

# returns nice x-axis, but black points
plot(time.val, inc, type="b", col="red")

#block 2
time2 <-
  ifelse (substr(time.val,5,6) == "Q1",
    as.Date(paste("1/1/",substr(time.val,1,4),sep=""),"%m/%d/%Y"),
  ifelse (substr(time.val,5,6) == "Q2",
    as.Date(paste("4/1/",substr(time.val,1,4),sep=""),"%m/%d/%Y"),
  ifelse (substr(time.val,5,6) == "Q3",
    as.Date(paste("7/1/",substr(time.val,1,4),sep=""),"%m/%d/%Y"),
    as.Date(paste("10/1/",substr(time.val,1,4),sep=""),"%m/%d/%Y"))))

#returns red lines but the axis is the number of days since 1/1/1970
plot(time2, inc, type="b", col="red")



More information about the R-help mailing list