簡體   English   中英

如何使用 R 在同一圖表中繪制擬合值、觀察值和預測值

[英]How to plot fitted,observed and forecast values in the same graph using R

所以,我有一個 nnetar 模型,我想用不同的顏色和圖例在同一個圖中繪制我的擬合、觀察(實際)和預測。 這是一個時間序列數據,“y”是我的 ts() 對象。

fit<-nnetar(y,xreg = train_reg)

results<-forecast(fit,xreg = test_reg)

plot(results)

使用此代碼,我只有預測值和可視化,我知道我可以使用 results$fitted 來達到擬合值,而對於預測值,我可以使用 results$mean。

謝謝!

這很簡單,您正在尋找命令points() 運行plot()命令時,請確保寫入 type="n",然后使用points()命令填寫數據,如下所示

請在下一篇文章中提供數據。

在這里,我有一個假裝的數據框df ,它有兩列數據:

  • 投贊成票的人(百分比)
  • 就業百分比(意思是,該地區的就業率有多高)

這里的變量是任意的,但這只是為了說明你想要做什么。

這是df

df <- structure(list(employment = c(23, 14.6, 9.9, 20.1, 34.4, 13.8, 
                                    20.6, 37.2, 21.8, 17.3, 13.1, 16.8, 24.6, 12.6, 13.6, 24.4, 19.3, 
                                    20, 22.6, 27.4, 23.1, 10.7, 32.1, 22, 25.6, 25), yes = c(55.2, 
                                                                                             54.4, 63.5, 50.6, 39, 51.1, 48.5, 39.1, 59.4, 50.6, 44.1, 53.3, 
                                                                                             39.3, 58.8, 59.1, 58.1, 63.1, 54.6, 55.9, 68.2, 57.8, 58.2, 38.9, 
                                                                                             48.3, 49.9, 47.3)), class = "data.frame", row.names = c(NA, -26L
                                                                                             ))

運行您的模型並將擬合值添加到您的df

model<-lm(yes ~ employment, data = df)

df$fit <-predict(model) # add fitted, aka predicted, values to df

attach(df)
  • 我們還可以使用下面的代碼將置信區間添加到繪圖中,如果您願意,可以使用多邊形命令在置信區間中添加陰影

讓我們使用library(yarr)和函數function yarr::transparent()制作自定義透明顏色

library(yarrr)

par(mfrow = c(1, 1), cex=2, pch=10) # set plot window to desired conditions
plot(yes ~ employment, data = df, ylab = "Yes [%]", xlab="Employment [%]", type="n")
points(yes ~ employment)
points(fit~employment, col="red") # Note, these are the fitted values in red
newx <- seq(min(df$employment), max(df$employment), length.out=100)
preds <- predict(model, newdata = data.frame(employment=newx), interval = 'confidence')
polygon(c(rev(newx), newx), c(rev(preds[ ,3]), preds[ ,2]), col = yarrr::transparent("583", trans.val = .5), border = NA)
abline(lm(yes~foreigners),col="blue", lwd=2)
lines(newx, preds[ ,3], lty = 'dashed', col = 'blue', lwd=2)
lines(newx, preds[ ,2], lty = 'dashed', col = 'blue',lwd=2)

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM