I'd like to make some meaningful histograms of observations for each year. For example, here are a few dates in 1970 and 1971 (near the Unix epoch):
dates <- as.Date(c("1970-01-01", "1971-08-16", "1971-12-31"))
d <- hist(dates, "years", freq=TRUE)
d$breaks # -1 364 729
The default output shows a misleading x-axis, which is offset by 1-year. I have detailed this behaviour of breakpoints in a bug report if you want to know more (PR#16679).
I would like to work-around the behaviour in R 3.2.3 to make meaningful histograms, where the expected x-axis labels for this example are 1970, 1971 and 1972. I've attempted adjusting the breakpoints by one day, and re-plotting:
d$breaks <- d$breaks + 1
plot(d)
but the x-axis is no longer a Date type. Any ideas on how to get the expected output?
Another idea is to plot the midpoints of the histogram in the centre of each bar of the boxplot, which has the correct date. I just don't know if it is easy to do, despite being returned by hist
(see d$mids
from the example).
A workaround is to show the mids along the x-axis, with some hints from this Q/A.
# plot histogram without axes
d <- hist(dates, "years", freq=TRUE, xaxt="n")
# these Date casts are optional, and show some the structure of the breaks
d$mids <-d$mids + as.Date("1970-01-01") # "1970-07-01" "1971-07-01"
d$breaks <- d$breaks + as.Date("1970-01-01") # "1969-12-31" "1970-12-31" "1971-12-31"
# finish off the plot
axis.Date(1, at=d$mids)
axis(2)
box(bty="l")