在 plot.xts 中调整 xaxis

Adjusting xaxis in plot.xts

我想放大图表。下面代码中的图表使用了 2007 年到 2019 年的数据。我只想看 2012 年到 2015 年的图表。有人知道怎么做吗?

我试过 xlim = ("2012-01-01";"2015-01-01"),但没用。

library(quantmod)
getSymbols("AAPL")
plot.xts(AAPL[,6])

您只需对 xts-object 进行子集化即可缩放它:

xts_data <- AAPL[ , 6]
xts_zoom <- xts_data['2012/2015']
plot.xts(xts_zoom)

手动设置 xlim 不起作用的原因是 xlim 值是在 plot.xts() 本身内部计算的。例如,参见 plot.xts() 源代码的第 123-134 行:

   if (cs$Env$observation.based) {
        cs$Env$xycoords <- xy.coords(1:NROW(cs$Env$xdata[subset]))
        cs$set_xlim(c(1, NROW(cs$Env$xdata[subset])))
        cs$Env$xstep <- 1
    }
    else {
        xycoords <- xy.coords(.index(cs$Env$xdata[cs$Env$xsubset]), 
        cs$Env$xdata[cs$Env$xsubset][, 1])
        cs$Env$xycoords <- xycoords
        cs$Env$xlim <- range(xycoords$x, na.rm = TRUE)
        ...
    }

另一种选择是使用 quantmod 包本身的 built-in 缩放工具:

chartSeries(xts_data)
zoomChart('2012/2015')