rplottime-seriestimeserieschart

Legends on time series plots in R


How do I add legends to my plot below?

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)

Solution

  • If you convert portfolioPrices to a dataframe then add each line separately you can add a legend.

    The following code doesn't create the best looking plot/legend but you could improve it by playing about with the legend/plot arguments.

    Also, the lines could be added using a loop rather than being hard-coded.

    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
    )
    

    enter image description here