[英]Legends on time series plots in R
如何在下面的 plot 中添加圖例? 我查看了互聯網上的各種文章,但似乎沒有一篇能讓我有所收獲。 將不勝感激任何幫助。
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:對於模組 - 請不要關閉我的問題,我已經查看了網站上的其他類似帖子,但它們沒有幫助我。
如果您將portfolioPrices 轉換為dataframe 然后分別添加每一行,您可以添加一個圖例。
以下代碼不會創建最好看的情節/圖例,但您可以通過使用圖例/情節 arguments 來改進它。
此外,可以使用循環而不是硬編碼來添加行。
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
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.