【问题标题】:Legends on time series plots in RR中时间序列图的图例
【发布时间】:2022-01-20 00:42:37
【问题描述】:

如何在下面的情节中添加图例?我查看了互联网上的各种文章,但似乎没有一篇能让我有所收获。非常感谢任何帮助。

library(quantmod)
library(PerformanceAnalytics)
library(imputeTS)
library(PortfolioAnalytics)

tickers <- c("FB", "AAPL", "AMZN", "NFLX")
weights <- c(.25, .25, .25, .25)

portfolioPrices <- NULL
for (Ticker in tickers)
  portfolioPrices <- cbind(portfolioPrices,
                           getSymbols.yahoo(Ticker, from="2016-01-01", periodicity = "daily", auto.assign=FALSE)[,4])

plot(portfolioPrices, legend = tickers)

PS:致模组 - 请不要关闭我的问题,我已经查看了网站上的其他类似帖子,但它们没有帮助我。

【问题讨论】:

    标签: r plot time-series timeserieschart


    【解决方案1】:

    如果您将portfolioPrices 转换为数据框,然后分别添加每一行,您可以添加一个图例。

    以下代码不会创建最好看的情节/图例,但您可以通过使用图例/情节参数来改进它。

    此外,可以使用循环而不是硬编码来添加行。

    library(quantmod)
    library(PerformanceAnalytics)
    library(imputeTS)
    library(PortfolioAnalytics)
    
    tickers <- c("FB", "AAPL", "AMZN", "NFLX")
    weights <- c(.25, .25, .25, .25)
    
    portfolioPrices <- NULL
    for (Ticker in tickers)
      portfolioPrices <- cbind(
        portfolioPrices,
        getSymbols.yahoo(
          Ticker,
          from = "2016-01-01",
          periodicity = "daily",
          auto.assign = FALSE
        )[, 4]
      )
    portfolioPrices <- data.frame(portfolioPrices)
    
    
    plot(
      x = as.Date(rownames(portfolioPrices)),
      portfolioPrices$FB.Close,
      col = "black",
      type = "l",
      ylim = c(min(portfolioPrices), max(portfolioPrices)),
      main = "Stocks",
      xlab = "Date",
      ylab = "Price"
    )
    lines(x = as.Date(rownames(portfolioPrices)),
          portfolioPrices$AAPL.Close,
          col = "blue")
    lines(x = as.Date(rownames(portfolioPrices)),
          portfolioPrices$AMZN.Close,
          col = "green")
    lines(x = as.Date(rownames(portfolioPrices)),
          portfolioPrices$NFLX.Close,
          col = "red")
    
    legend(
      "topleft",
      legend = tickers,
      col = c("black", "blue", "green", "red"),
      cex = 0.5,
      lwd = 2
    )
    

    【讨论】:

      最近更新 更多