【问题标题】:How do I plot multiple lines on the same graph?如何在同一图表上绘制多条线?
【发布时间】: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


【解决方案1】:

您似乎混淆了几件事:

  1. fitted 通常不适用于arima 类的对象。通常,您可以先加载forecast 包,然后再使用fitted。 但是由于您没有访问forecast 包的权限,因此您不能使用fitted(fit):它总是返回NULLI had problems with fitted before.

  2. 您想将实际序列 (x) 与拟合序列 (y) 进行比较,但在第一次尝试中,您使用的是残差 (e = x - y)

  3. 你说你正在使用 ggplot2 但实际上你没有

所以这里有一个小例子,说明如何在没有 ggplot 的情况下绘制实际序列和拟合序列。

set.seed(1)

x <- cumsum(rnorm(10))
y <- stats::arima(x, order = c(1, 0, 0))

plot(x, col = "red", type = "l")
lines(x - y$residuals, col = "blue")

我希望这个答案可以帮助您重回正轨。

【讨论】:

  • 很好的答案!您能否在原始帖子中澄清“选项2”?为什么只有“一种颜色”线? 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") # 绘制拟合值 legend("topleft", legend = c("original","fitted"), col = c("black","re​​d" ),lty = 1)
  • 第二种方法不起作用,因为fitted(fit) 返回NULL。答案中提到了这一点。+
  • @Cett : 有没有办法解决这个问题并仍然使用“fitted”选项?
  • @stats555 如果你想使用arima 类的对象,你不能使用fitted。但是,您可以通过复制forecast:::fitted.Arima 的源代码来定义自己的fitted 版本,称为fitted.arima。如果这样做,您将看到 Arima 对象的 fitted 的定义与我在答案中定义的一样。
猜你喜欢
  • 2020-03-02
  • 2017-02-24
  • 1970-01-01
  • 1970-01-01
  • 2020-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多