Use hours on the x-axis when plotting with zoo in R
-
24-02-2021 - |
Question
I have the following code in R:
z = read.zoo(filename, sep=',', header=T, index = 1:2, FUN=f)
plot(z[,1], col='red', lty=1, xaxt="n")
Which produces a line plot of the time series of my data, without any x-axis. I want to then add an x-axis with labels in hours, so I try the following (my conversion of the examples in the zoo FAQ):
tt = time(z)
m = unique(hours(tt))
axis(side = 1, at = m, labels=substr(m, 1, 2))
But no axis appears. What am I doing wrong here? I'm following the examples as closely as possible, but changing it from getting months to getting hours. Any ideas?
In case it helps, here are the first few lines of the output of z
:
AOT_500 Water.cm.
(04/27/10 06:53:26) 0.134940 1.403318
(04/27/10 07:01:26) 0.147529 1.425749
(04/27/10 07:07:15) 0.161837 1.411711
(04/27/10 07:12:05) 0.155312 1.415916
(04/27/10 07:21:36) 0.161960 1.438144
(04/27/10 07:34:29) 0.175276 1.426818
(04/27/10 07:50:08) 0.169452 1.435454
(04/27/10 08:09:39) 0.181987 1.437278
(04/27/10 08:50:58) 0.159755 1.372659
(04/27/10 09:04:12) 0.168336 1.348832
(04/27/10 09:10:04) 0.201690 1.383709
Update: As requested - the output of dput(head(z,10))
structure(c(0.13494, 0.147529, 0.161837, 0.155312, 0.16196, 0.175276,
0.169452, 0.181987, 0.159755, 0.168336, 1.403318, 1.425749, 1.411711,
1.415916, 1.438144, 1.426818, 1.435454, 1.437278, 1.372659, 1.348832
), .Dim = c(10L, 2L), .Dimnames = list(NULL, c("AOT_500", "Water.cm."
)), index = structure(c(14726.2871064815, 14726.292662037, 14726.2967013889,
14726.3000578704, 14726.3066666667, 14726.3156134259, 14726.3264814815,
14726.3400347222, 14726.3687268519, 14726.3779166667), format = structure(c("m/d/y",
"h:m:s"), .Names = c("dates", "times")), origin = structure(c(1,
1, 1970), .Names = c("month", "day", "year")), class = c("chron",
"dates", "times")), class = "zoo")
Solution
At the moment you are only giving the y values to the plot-method. I found the time calculations to be quite a mess and decided to instead use the plot method without the axis. Just subtract the truncated time from the time to give hours and plot.zoo figures it out nicely for you:
require(xts); require(chron)
mm <- times(tt)
plot((mm-trunc(mm) ), z[,1], col='red', lty=1, type="b", xlab="Time of Day")
OTHER TIPS
Take a look at the intermediate data. m
is a number, but you use it in the axis
function like you expect it to be a string. Even if it were a string, it wouldn't work because at=
needs to be the same class as the index of the object you're plotting (chron in this case).
The code below does what I think you were trying to do:
# find the hourly sections of the chron index
m <- trunc((tt-trunc(tt))*24)/(24)
# find the minimum index value for each hour
l <- tapply(tt, m, min)
# plot the series
plot(z[,1], col='red', lty=1, xaxt="n", xlab="")
# add the axis
axis(side=1, at=l, labels=unique(m), las=2)