【问题标题】:In R, how can I add a legend to a plot of an XTS object?在 R 中,如何在 XTS 对象的图中添加图例?
【发布时间】:2021-11-28 13:28:40
【问题描述】:

以下创建一个两列 XTS 对象作为示例数据。

quantmod::getSymbols(c('SPY','IWM'),
                     src  = 'yahoo', 
                     from = '2010-01-01', 
                     to   = '2021-02-01',
                     auto.assign = TRUE, 
                     warnings = FALSE)
close <- cbind(SPY$SPY.Close, IWM$IWM.Close)

下面将两列作为时间的函数进行了很好的绘制,但没有出现图例。 legend 命令看起来像它在执行时没有返回错误,但在绘图上没有创建图例。

qualityTools::plot(close, col=1:ncol(close))
legend('topleft', legend=colnames(close), 
       col=1:ncol(close), lty=1, cex=0.5)

Plot of XTS object without legend

我还尝试了以下方法。它绘制了两列的图,我得到了一个图例。但是,as.ts() 函数将 XTS 对象的时间索引转换为从 1 到 ncol(close) 的增量计数器,而不是实际日期。因此,图中的时间轴也是一个简单的增量计数器,而不是实际日期。

closets <- stats::as.ts(close)
qualityTools::plot(closets, plot.type='single', col = 1:ncol(closets))
legend('topleft', legend=colnames(closets), 
       col=1:ncol(closets), lty=1, cex=0.5)

Plot of TS object with legend but a period counter rather than real time axis

关于如何在 XTS 对象的第一次情节尝试中获得图例的任何想法?如果没有,我会在 TS 对象的第二次绘图尝试中选择更好的时间轴。

【问题讨论】:

    标签: r plot legend xts


    【解决方案1】:

    当您使用 quantmod 时,您可以使用 chartSeries 或仅使用 plot(这是对 plot.xts 的调用)来绘制时间序列。

    在编写包 qualityTools 时不再在 cran 上,但由于包维护者尚未修复的一些错误而被存档。

    一个使用plot的例子:

    plot.xts(SPY$SPY.Close, ylim = c(0,500), main = "")
    lines(IWM$IWM.Close)
    addLegend("topleft", on=1, 
              legend.names = c("SPY", "IWM"), 
              lty=c(1, 1), lwd=c(2, 1),
              col=c("black", "blue"))
    

    【讨论】:

    • 谢谢,这很有帮助。看起来我真的只需要两行来处理 XTS 对象中的任意数量的列: xts::plot.xts(close); xts::addLegend("topleft", legend.names = names(close), lty=1, col=1:ncol(close))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    • 2020-05-07
    • 2021-07-27
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    相关资源
    最近更新 更多