在调用 zoom 函数(允许用户通过单击缩放的最左侧和最右侧边界以交互方式更改图表的缩放)后,是否可以显示结果子集?
我想要这个的原因:
- 根据我添加的自定义 TA 为我的图表设置适当的 yrange,否则将不可见,因为自动 yrange 仅基于传递给对 chartSeries 的原始调用的时间序列
- 实现左右平移图表的功能
不涉及获取当前子集的这两个目标的解决方法也会有所帮助。目前我能想到的唯一选择是避免使用交互式缩放功能,而只使用图表缩放。
首先要知道的是为什么zoomChart()
返回你想要的值,但zooom()
没有。
zoomChart()
之所以这样做,是因为它调用了reChart()
以该行结尾的函数invisible(chob)
。(chob
是您所追求的对象的名称。)
zooom()
不这样做。它调用zoomChart()
,但它没有安排chob
离开zoomChart()
正在评估的环境。但是,您可以通过创建修改后的版本来做到这一点zooom()
我通过首先转储zooom
到一个文件然后创建一个名为的编辑函数来做到这一点zooom2
:
require(quantmod)
dump("zooom", file="zooom2.R")
我所做的三个编辑是:
将调用替换为get.chob()
调用quantmod:::get.chob()
。这是必需的,因为与 不同zooom
,zooom2
它没有namespace:quantmod
作为其封闭环境。
将 的输出分配zoomChart()
给对象chob
。
通过以 结束函数返回chob
调用环境invisible(chob)
。
这是修改后的功能:
zooom2 <-
function (n = 1, eps = 2)
{
for (i in 1:n) {
cat("select left and right extremes by clicking the chart\n")
points <- locator(2)
if (abs(diff(points$x)) < eps) {
zoomChart()
}
else {
usr <- par("usr")
xdata <- quantmod:::get.chob()[[2]]@xdata
xsubset <- quantmod:::get.chob()[[2]]@xsubset
sq <- floor(seq(usr[1], usr[2], 1))
st <- which(floor(points$x[1]) == sq)/length(sq) *
NROW(xdata[xsubset])
en <- which(floor(points$x[2]) == sq)/length(sq) *
NROW(xdata[xsubset])
sorted <- sort(c(st, en))
st <- sorted[1]
en <- sorted[2] * 1.05
chob <- zoomChart(paste(index(xdata[xsubset])[max(1, floor(st),
na.rm = TRUE)], index(xdata[xsubset])[min(ceiling(en),
NROW(xdata[xsubset]), na.rm = TRUE)], sep = "::"))
}
}
cat("done\n")
invisible(chob)
}
您可以将该函数获取或粘贴回您的 R 会话中,然后像这样使用它(例如):
data(sample_matrix)
chartSeries(sample_matrix)
d <- zooom2()
# Click to interactively zoom in
# extract the data visible in the selected region
d_sub <- d@xdata[d@xsubset,]
head(d_sub)
# Open High Low Close
# 2007-03-28 48.33090 48.53595 48.33090 48.53595
# 2007-03-29 48.59236 48.69988 48.57432 48.69988
# 2007-03-30 48.74562 49.00218 48.74562 48.93546
# 2007-03-31 48.95616 49.09728 48.95616 48.97490
# 2007-04-01 48.94407 48.97816 48.80962 48.87032
# 2007-04-02 48.90488 49.08400 48.90488 49.06316
如果这对您有用,您可能希望将其添加到quantmod
源代码中,然后重新编译您自己的软件包版本。
希望这可以帮助。