【发布时间】:2021-03-26 21:14:26
【问题描述】:
我正在使用 R。我正在尝试使用 ggplot2 中的“lines”命令来显示统计模型(arima、时间序列)的预测值与实际值。然而,当我运行代码时,我只能看到一种颜色的线条。
我在 R 中模拟了一些数据,然后尝试绘制显示实际与预测的图:
#set seed
set.seed(123)
#load libraries
library(xts)
library(stats)
#create data
date_decision_made = seq(as.Date("2014/1/1"), as.Date("2016/1/1"),by="day")
date_decision_made <- format(as.Date(date_decision_made), "%Y/%m/%d")
property_damages_in_dollars <- rnorm(731,100,10)
final_data <- data.frame(date_decision_made, property_damages_in_dollars)
#aggregate
y.mon<-aggregate(property_damages_in_dollars~format(as.Date(date_decision_made),
format="%W-%y"),data=final_data, FUN=sum)
y.mon$week = y.mon$`format(as.Date(date_decision_made), format = "%W-%y")`
ts = ts(y.mon$property_damages_in_dollars, start = c(2014,1), frequency = 12)
#statistical model
fit = arima(ts, order = c(4, 1, 1))
这是我绘制图表的尝试:
#first attempt at plotting (no second line?)
plot(fit$residuals, col="red")
lines(fitted(fit),col="blue")
#second attempt at plotting (no second line?)
par(mfrow = c(2,1),
oma = c(0,0,0,0),
mar = c(2,4,1,1))
plot(ts, main="as-is") # plot original sim
lines(fitted(fit), col = "red") # plot fitted values
legend("topleft", legend = c("original","fitted"), col = c("black","red"),lty = 1)
#third attempt (plot actual, predicted and 5 future values - here, the actual and future values show up, but not the predicted)
pred = predict(fit, n.ahead = 5)
ts.plot(ts, pred$pred, lty = c(1,3), col=c(5,2))
但是,这些似乎都不能正常工作。有人可以告诉我我做错了什么吗? (注意:我用于工作的计算机没有互联网连接或 USB 端口 - 它只有 R 和一些预加载的包。我无权访问 forecast 包。)
谢谢
来源:
【问题讨论】:
-
您提到了“ggplot2”,但您发布的代码并未使用该包。
标签: r plot time-series data-visualization