R中时间序列图的图例
Posted
技术标签:
【中文标题】R中时间序列图的图例【英文标题】:Legends on time series plots in R 【发布时间】: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:致模组 - 请不要关闭我的问题,我已经查看了网站上的其他类似帖子,但它们没有帮助我。
【问题讨论】:
【参考方案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
)
【讨论】:
以上是关于R中时间序列图的图例的主要内容,如果未能解决你的问题,请参考以下文章
将ggplot2包装在plotly R中时,图例中的额外变量
R语言ggplot2可视化分面图(faceting): 堆叠柱状图的分面图编写自定义函数在分面图的左侧添加图例信息(legend)