R ggplot2:使用预测为时间序列添加图例

时间:2017-03-04 16:29:25

标签: r ggplot2 time-series

我一直在看这几个小时难过。我遇到了一些建议,我需要添加aes()并为geom_lines指定颜色,但这不会产生任何结果 - 可能因为我也有一些预测?我真的不太确定。

在任何情况下,我都将我的代码放在下面,非常感谢您提供的任何帮助。

install.packages("fpp")
library(fpp)
data("books")
library(ggplot2)
paperback <- books[,1]
fit1    <-  ses(paperback,  alpha   =   0.2,    initial =   "simple",   h   =   3)
fit2    <-  ses(paperback,  alpha   =   0.6,    initial =   "simple",   h   =   3)
fit3    <-  ses(paperback,  h   =   3)

autoplot(paperback,
     xlab="Day",    main="", size = 20) + 
     geom_line(data = paperback, colour = "black", aes(colour="black")) + 
     geom_line(data = fitted(fit1), colour = "blue", linetype = 2, aes(colour="blue")) + 
     geom_line(data = fitted(fit2), colour = "red", linetype = 2, aes(colour="red")) + 
     geom_line(data = fitted(fit3), colour = "green", linetype = 2, aes(colour = "green")) + 
     geom_line(data = fit1$mean, colour = "blue", linetype = 2) + 
     geom_line(data = fit2$mean, colour = "red", linetype = 2) + 
     geom_line(data = fit3$mean, colour = "green", linetype = 2)

1 个答案:

答案 0 :(得分:0)

我建议直接绘制预测对象:

install.packages("fpp")
require("fpp"); require("books"); require("ggplot2"); require("ggfortify")
data("books")

paperback <- books[,1]

fit1    <-  ses(paperback,  alpha   =   0.2,    initial =   "simple",   h   =   3)
fit2    <-  ses(paperback,  alpha   =   0.6,    initial =   "simple",   h   =   3)
fit3    <-  ses(paperback,  h   =   3)

par(mfrow = c(1,3))
plot(fit1)
plot(fit2)
plot(fit3)

这会产生:

enter image description here

如果你想用ggplot来做,你可以这样做:

X <- cbind(model1 = fit1$mean, model2 = fit2$mean, model3 = fit3$mean)
df <- cbind(paperback, X)
colnames(df) <- c("paperback", "model1", "model2", "model3")
autoplot(df)

产生

enter image description here