我试图在同一个情节中绘制一些线条。 x因子由日期确定,y因子由数字确定。我最初加载数据,将其存储在列表中并保存日期的最小值和最大值:
stocks <- list()
stocks.min <- 0
stocks.max <- 0
stocks.min.date <- NULL
stocks.max.date <- NULL
for (name in names(files))
{
stocks[[name]] <- read.csv(files[[name]], sep=";")
# Convert to date in R
stocks[[name]]$Date <- as.Date(stocks[[name]]$Date, "%d/%m/%Y")
# Sets max value for ylim in the plotting
if (stocks.max < max(stocks[[name]]$Close))
{
stocks.max <- max(stocks[[name]]$Close)
}
# Sets the date value for the xlim in the plot
if (is.null(stocks.min.date) || min(stocks[[name]]$Date) < stocks.min.date)
{
stocks.min.date <- min(stocks[[name]]$Date)
}
if (is.null(stocks.max.date) || max(stocks[[name]]$Date) > stocks.max.date)
{
stocks.max.date <- max(stocks[[name]]$Date)
}
}
之后,我使用上面的值创建一个空图:
plot(0, xlab="Time", ylab="Closing Prices", main="Stock Values",
xlim=c(stocks.min.date, stocks.max.date), ylim=c(stocks.min, stocks.max))
然后我添加了包含数据的行:
for (name in names(stocks))
{
lines(x=stocks[[name]]$Date, y=stocks[[name]]$Close, col=colors[[name]], type="l",
lwd=2)
}
绘制图表时,数据会正确显示,但会将日期显示为数字而不是x轴上的日期,如下图所示:
如何更正此问题?
答案 0 :(得分:1)
我强烈建议使用标准化系列来绘制您拥有的股票数据。 quantmod
在这里有很多帮助。它解决了两个目的 -
这是我通常用于我的目的。
library(quantmod)
tickers <- c('GOOG', 'MSFT', 'AAPL', 'AMZN')
getSymbols(tickers, src = 'yahoo', from = '2015-01-01')
normalise <- function(x) x/as.numeric(x)[1] - 1
chart_theme <- chart_theme()
chart_theme$col$line.col <- "red"
chart_Series(normalise(Cl(GOOG)), theme = chart_theme)
add_TA(normalise(Cl(MSFT)), on = 1, col = "black", lty = 1)
add_TA(normalise(Cl(AMZN)), on = 1, col = "blue", lty =1)
add_TA(normalise(Cl(AAPL)), on = 1, col = "darkgreen", lty =2)
希望这有帮助。