this 웹 사이트에서 Davenport는 ggplot2
이라는 arima 예측을 임의의 데이터 집합의 예제에 플롯하기 위해 here을 게시했습니다. 오류 메시지없이 그의 예를 따를 수 있습니다. 내 데이터를 사용할 때ggplot2 및 funggcast 함수로 예측
, 내가 경고로 끝나는 것 :
1: In window.default(x, ...) : 'end' value not changed
2: In window.default(x, ...) : 'end' value not changed
를 내가이 명령 pd <- funggcast(yt, yfor)
를 호출 할 때 그것 때문에 내 데이터 end = c(2013)
을에 표시 데이터에 문제가 일어나는 것을 알고있다 . 그러나 나는 그것을 고치는 방법을 모른다.
이
내가 사용하는 코드입니다 :library(ggplot2)
library(zoo)
library(forecast)
myts <- ts(rnorm(55), start = c(1960), end = c(2013), freq = 1)
funggcast <- function(dn, fcast){
en <- max(time(fcast$mean)) # Extract the max date used in the forecast
# Extract Source and Training Data
ds <- as.data.frame(window(dn, end = en))
names(ds) <- 'observed'
ds$date <- as.Date(time(window(dn, end = en)))
# Extract the Fitted Values (need to figure out how to grab confidence intervals)
dfit <- as.data.frame(fcast$fitted)
dfit$date <- as.Date(time(fcast$fitted))
names(dfit)[1] <- 'fitted'
ds <- merge(ds, dfit, all.x = T) # Merge fitted values with source and training data
# Extract the Forecast values and confidence intervals
dfcastn <- as.data.frame(fcast)
dfcastn$date <- as.Date(as.yearmon(row.names(dfcastn)))
names(dfcastn) <- c('forecast','lo80','hi80','lo95','hi95','date')
pd <- merge(ds, dfcastn,all.x = T) # final data.frame for use in ggplot
return(pd)
}
yt <- window(myts, end = c(2013)) # extract training data until last year
yfit <- auto.arima(myts) # fit arima model
yfor <- forecast(yfit) # forecast
pd <- funggcast(yt, yfor) # extract the data for ggplot using function funggcast()
ggplot(data = pd, aes(x = date,y = observed)) + geom_line(color = "red") + geom_line(aes(y = fitted), color = "blue") + geom_line(aes(y = forecast)) + geom_ribbon(aes(ymin = lo95, ymax = hi95), alpha = .25) + scale_x_date(name = "Time in Decades") + scale_y_continuous(name = "GDP per capita (current US$)") + theme(axis.text.x = element_text(size = 10), legend.justification=c(0,1), legend.position=c(0,1)) + ggtitle("Arima(0,1,1) Fit and Forecast of GDP per capita for Brazil (1960-2013)") + scale_color_manual(values = c("Blue", "Red"), breaks = c("Fitted", "Data", "Forecast"))
편집 : 나는 forecast
과 ggplot2
와 함께 사용할 수있는 기능을 다른 블로그 here을 발견하지만 수 있다면 나는 위의 방법을 사용하고 싶습니다 내 실수를 찾아야 해. 누군가?
Edit2가 : 나는 아래로 아래의 그래프를 얻을 것보다 나는 내 데이터 here으로 업데이트 된 코드를 실행합니다. end = c(2023)
을 mtys
으로 변경하지 않았 으면 예측 된 값과 예상 값을 병합하지 않을 것입니다.
myts <- ts(WDI_gdp_capita$Brazil, start = c(1960), end = c(2023), freq = 1)
funggcast <- function(dn, fcast){
en <- max(time(fcast$mean)) # Extract the max date used in the forecast
# Extract Source and Training Data
ds <- as.data.frame(window(dn, end = en))
names(ds) <- 'observed'
ds$date <- as.Date(time(window(dn, end = en)))
# Extract the Fitted Values (need to figure out how to grab confidence intervals)
dfit <- as.data.frame(fcast$fitted)
dfit$date <- as.Date(time(fcast$fitted))
names(dfit)[1] <- 'fitted'
ds <- merge(ds, dfit, all = T) # Merge fitted values with source and training data
# Extract the Forecast values and confidence intervals
dfcastn <- as.data.frame(fcast)
dfcastn$date <- as.Date(paste(row.names(dfcastn),"01","01",sep="-"))
names(dfcastn) <- c('forecast','lo80','hi80','lo95','hi95','date')
pd <- merge(ds, dfcastn,all.x = T) # final data.frame for use in ggplot
return(pd)
} # ggplot function by Frank Davenport
yt <- window(myts, end = c(2013)) # extract training data until last year
yfit <- auto.arima(yt) # fit arima model
yfor <- forecast(yfit) # forecast
pd <- funggcast(myts, yfor) # extract the data for ggplot using function funggcast()
ggplot(data = pd, aes(x = date, y = observed)) + geom_line(color = "red") + geom_line(aes(y = fitted), color = "blue") + geom_line(aes(y = forecast)) + geom_ribbon(aes(ymin = lo95, ymax = hi95), alpha = .25) + scale_x_date(name = "Time in Decades") + scale_y_continuous(name = "GDP per capita (current US$)") + theme(axis.text.x = element_text(size = 10), legend.justification=c(0,1), legend.position=c(0,1)) + ggtitle("Arima(0,1,1) Fit and Forecast of GDP per capita for Brazil (1960-2013)") + scale_color_manual(values = c("Blue", "Red"), breaks = c("Fitted", "Data", "Forecast")) + ggsave((filename = "gdp_forecast_ggplot.pdf"), width=330, height=180, units=c("mm"), dpi = 300, limitsize = TRUE)
거의 완벽한 그래프는 내가 얻을 :
하나 추가 질문 : 어떻게이 그래프에 범례를받을 수 있나요? 내가 myts
에 대한 end = c(2013)
을 설정하면
, 나는 처음과 같은 그래프를 얻을 :
가 귀하의 회신, 좋은 감사합니다! 나는 하나의 후속 질문이있다. 내 데이터는 사실 무작위가 아니며 54 건의 관측 (1960 년에서 2013 년까지)으로 구성됩니다 (ggtitle 참조). 따라서 나는 고의적으로'myts '를 연장 할 수 없다. 어쨌든 'myts'보다 어차피 그렇게하는 것은 시작부터 반복되는 관찰을 반복합니다. 어떻게 이것을 피할 수 있습니까? 'NA' 삽입!? 또는 다른 말로하면 (그래프를 보면) : 빨간색 선이 회색 영역을 벗어나는 것을 어떻게 피할 수 있습니까? –
'pd' 할당 라인과'myts' 설명을 편집하여 여러분이 작성한'경고 '를 얻었습니다. 왜냐하면 2013 년이 훈련 시리즈의 끝이고 2023 년까지 예측하기 때문에'en'은 2023입니다 .최종 데이터 프레임에서 2013 년 이후에 관찰 된 값과 맞는 값에 대해 NAs가 자동으로 추가됩니다. – NicE
빠른 편집을 해주셔서 감사합니다. 새로운'pd '할당을 나타낼 수 있습니까? 코드에서 찾을 수 없습니다!? –