简体   繁体   English

如何更改 plot.zoo plot 中的(数量)x 轴刻度? (轴()失败)

[英]How to change the (number of) x-axis ticks in a plot.zoo plot? (axis() fails)

The following time series plot with plot.zoo() shows a weird number of (only one) x-axis ticks.以下时间序列 plot 和plot.zoo()显示了奇怪数量的(只有一个)x 轴刻度。 How can one convince plot.zoo() to show more x-axis ticks?如何说服plot.zoo()显示更多的 x 轴刻度?

## 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:我尝试了通常的方法来更改 x 轴,但由于某种原因 (?) axis()在这里不受尊重:

## 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()的版本:

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.问题中的代码调用plot.zoo直接调用 zoo 方法。 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.) (必须直接调用该方法的主要情况是泛型出现在当前未加载的不同 package 中;但是, plot不是这种情况,因为它是基础 ZE1E1D3D40573127E9DAF1283 的一部分。)

  • ?axTicksByTime says This function is written for internal use ?axTicksByTime这个 function 是为内部使用而编写的

  • if you want to use axTicksByTime anyways then note that it returns indexes into the time vector and not the times themselves.如果您仍然想使用axTicksByTime ,请注意它将索引返回到时间向量而不是时间本身。 That is why nothing appeared when the question used the axis command.这就是为什么当问题使用axis命令时什么都没有出现。

If you want to use axTicksByTime anyways and use it with the zoo method of plot then it would be done like this.如果您仍然想使用axTicksByTime并将其与plot的 zoo 方法一起使用,那么可以这样做。

plot(as.zoo(ts), xaxt = "n")
ticks <- axTicksByTime(ts, format = "%Y %m")
labels <- names(ticks)
axis(1, at = time(ts)[ticks], labels = labels) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM