The following time series plot with plot.zoo()
shows a weird number of (only one) x-axis ticks. How can one convince plot.zoo()
to show more x-axis ticks?
## Create a dummy time series
library(xts)
start <- as.Date("2020-04-01")
end <- as.Date("2021-06-02")
dat <- seq(start, end, length.out = 226)
set.seed(271)
ts <- xts((1:226) + rnorm(226, sd = 1/3), order.by = dat)
plot.zoo(ts) # => only one x-axis tick displayed
I tried the usual to change the x-axis, but for some reason (?) axis()
is not respected here:
## Trial
plot.zoo(ts, xaxt = "n")
ticks <- axTicksByTime(index(ts))
labels <- names(ticks)
axis(1, at = ticks, labels = labels) # => no x-axis ticks displayed
If you need more details, just let me know.
Here is a version based on standard plot()
:
plot(as.numeric(ts), type = "l", xaxt = "n")
ticks <- axTicksByTime(index(ts), format.labels = "%Y-%m-%d")
labels <- names(ticks)
axis(1, at = ticks, labels = labels)
And a somewhat nicer one:
plot(as.numeric(ts), type = "l", xaxt = "n", xlab = "", ylab = "ts")
ticks <- axTicksByTime(index(ts), format.labels = "%Y-%m")
labels <- names(ticks)
axis(1, at = ticks, labels = labels, las = 2)
There are several problems with the code in the question:
the code in the question calls plot.zoo
which is calling the zoo method directly. In general, code should call the generic and let it dispatch the method rather than calling the method directly. (The main situation where one must call the method directly is when the generic appears in a different package that is not currently loaded; however, that is not the case for plot
since it is part of base R.)
?axTicksByTime
says This function is written for internal use
if you want to use axTicksByTime
anyways then note that it returns indexes into the time vector and not the times themselves. That is why nothing appeared when the question used the axis
command.
If you want to use axTicksByTime
anyways and use it with the zoo method of plot
then it would be done like this.
plot(as.zoo(ts), xaxt = "n")
ticks <- axTicksByTime(ts, format = "%Y %m")
labels <- names(ticks)
axis(1, at = time(ts)[ticks], labels = labels)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.