Andri Signorell - 1 year ago 132
R Question

# How to get axis ticks on a Date axis

For usual axis we can get the tick values with axTicks. If x is a Date, this attempt fails.

``````x <- sort(sample(seq(as.Date("2000-01-01"), as.Date("2010-12-31"), by=1), 50))
y <- runif(50)
plot(y~x, type="l", col="steelblue")

axTicks(1)
abline(v=axTicks(1))
``````

axTicks returns values, but obviously not the ultimately used ones. How can we get the used ticks?

I think the tick positions for the plot are created by `axis.Date`. To get the positions you can copy the relevant parts of `axis.Date` in your own function:

``````dateTicks <- function(x, side = 1) {
##  This functions is almost a copy of axis.Date
x <- as.Date(x)
range <- par("usr")[if (side%%2)
1L:2L
else 3:4L]
range[1L] <- ceiling(range[1L])
range[2L] <- floor(range[2L])
d <- range[2L] - range[1L]
z <- c(range, x[is.finite(x)])
class(z) <- "Date"
if (d < 7)
format <- "%a"
if (d < 100) {
z <- structure(pretty(z), class = "Date")
format <- "%b %d"
}
else if (d < 1.1 * 365) {
zz <- as.POSIXlt(z)
zz\$mday <- 1
zz\$mon <- pretty(zz\$mon)
m <- length(zz\$mon)
m <- rep.int(zz\$year[1L], m)
zz\$year <- c(m, m + 1)
z <- as.Date(zz)
format <- "%b"
}
else {
zz <- as.POSIXlt(z)
zz\$mday <- 1
zz\$mon <- 0
zz\$year <- pretty(zz\$year)
z <- as.Date(zz)
format <- "%Y"
}
keep <- z >= range[1L] & z <= range[2L]
z <- z[keep]
z <- sort(unique(z))
class(z) <- "Date"
z
}
``````

If you in contrast look at the source for `axTicks` you can see that for dates it boils down to `seq.int(axp[1L], axp[2L], length.out = 1L + abs(axp[3L]))` with `axp = par("xaxp")`. So it's just converting the dates to numeric and dividing the resulting range evenly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download