2017-03-04 46 views
0

我一直在尋找這個小時難倒。我遇到過許多建議,我需要添加aes()並將顏色分配給geom_lines,但這不會產生任何內容 - 可能是因爲我也有一些預測?我真的不太確定。R ggplot2:將圖例添加到具有預測的時間序列

在任何情況下,我已將我的代碼放在下面,並非常感謝您提供的任何幫助。

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) 

回答

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

相關問題