Question

I'm following up a response by @Gavin Simpson to an earlier question about x-axis tick labeling with a question about non-sequenced tick labels. Here is his response example to set up the problem:

set.seed(53)
f <- rnorm(700, 2)
dates <- seq(as.Date("04/01/2012", format = "%d/%m/%Y"),
             by = "days", length = length(f))
head(f)
op <- par(mar = c(7,4,4,2) + 0.1) ## more space for the labels
plot(dates, f, xaxt = "n", ann = FALSE)
labDates <- seq(as.Date("01/01/2012", format = "%d/%m/%Y"), tail(dates, 1),
                by = "months")
axis.Date(side = 1, dates, at = labDates, format = "%b %y", las = 2)
title(ylab = "f") ## draw the axis labels
title(xlab = "dates", line = 5) ## push this one down a bit in larger margin
par(op) ## reset margin

However, rather than a sequenced set of x-axis tick labels beginning at "Jan 12" and ending "Dec 13" I would like to only label several dates that are non-sequential and of a different length than f, such as March 3, 2012, April 27, 2012, October 20, 2012, and May 8, 2013, while the remainder of the plot persists. So I set up a vector of dates to call but get tripped up after that:

set.seed(53)
f <- rnorm(700, 2)   # the count doesn't matter
MyDates<-c("03/03/12", "04/27/13","10/20/12", "05/08/13")   # non-sequential char string of dates not equal to f
plot(MyDates, f, xaxt = "n", ann = FALSE)
axis.Date(1, MyDates, at=c(1,length(MyDates), ??????))   #not complete and not right

So my question is how do I label a set of non-sequential x-axis tick marks of a different length than the data?

I would also like to add vertical lines at the dates I choose, which I am aware may be done with abline(), but have yet to get there since I'm laboring over this axis.Date issue.

Était-ce utile?

La solution

First, convert your selected dates from character to Date (using the right format string):

MyDates <- as.Date(MyDates, format = "%m/%d/%y")
# [1] "2012-03-03" "2013-04-27" "2012-10-20" "2013-05-08"

class(MyDates)
# [1] "Date"

Then you can add your axis with ticks at those points only:

axis.Date(side = 1, at = MyDates, format = "%b %y", las = 2)

That short axis looks ugly? Add the first and last date:

axis.Date(side = 1, at = c(min(dates), MyDates, max(dates)), format = "%b %y", las = 2)

Want to stretch the axis but not have the first/last labels? Don't print them:

axis.Date(side = 1, at = c(min(dates), MyDates, max(dates)), 
    labels = c("", format(MyDates, "%b %y"), ""), las = 2)

Or instead, draw a long axis first without labels:

axis.Date(side = 1, at = c(min(dates), max(dates)), labels=FALSE)
axis.Date(side = 1, at = MyDates, format = "%b %y", las = 2)

Vertical lines:

abline(v=MyDates)
abline(v=MyDates, lty="dashed", col="red")
# etc.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top