2015-01-30 2 views
2

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")) 

편집 : 나는 forecastggplot2와 함께 사용할 수있는 기능을 다른 블로그 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) 

거의 완벽한 그래프는 내가 얻을 : enter image description here

하나 추가 질문 : 어떻게이 그래프에 범례를받을 수 있나요? 내가 myts에 대한 end = c(2013)을 설정하면

, 나는 처음과 같은 그래프를 얻을 :

enter image description here

답변

5

씨 데븐 포트의 분석과 당신이 만들려고하는 음모와 다른 몇 가지 포인트가 있습니다 . 첫 번째는 그가 아리마 예측을 일부 관측 된 데이터와 비교한다는 것입니다. 그 이유는 그가 전체 시간 계열 중 일부, 즉 교육 세트에서 모델을 훈련하는 이유입니다. 이렇게하려면, 당신은 당신의 초기 시간 시리즈는 더 이상해야한다 :

myts <- ts(rnorm(55), start = c(1960), end = c(2023), freq = 1) 

을 그런 다음 2013 년까지 교육 선택 스크립트의 말 :

yt <- window(myts, end = c(2013)) # extract training data until last year 

모델이 훈련되어야한다 훈련 세트가 아닌 전체 시계열에, 당신은에 yfit 라인을 변경해야합니다 있도록 :

yfit <- auto.arima(yt) # fit arima model 

을 그리고 전체 시계열을 사용하여 funggcast 함수를 호출, 그것 때문에

dfcastn$date <- as.Date(as.yearmon(row.names(dfcastn))) 

하려면 :

dfcastn$date <- as.Date(paste(row.names(dfcastn),"01","01",sep="-")) 

pd <- funggcast(myts, yfor) 

마지막으로, 그는 자신의 funggcast 기능에, 그래서이 줄을 변경, 월, 년이 날짜를 사용하여 관찰 및 장착 데이터를 필요

관찰 된 데이터와 병합하려면 2014를 2014-01-01로 변경해야하는 등 모델에서 예측 한 값을 날짜로 변경해야하기 때문입니다.

모든 변경 후, 코드는 다음과 같습니다

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(paste(row.names(dfcastn),"01","01",sep="-")) 
     names(dfcastn) <- c('forecast','lo80','hi80','lo95','hi95','date') 

     pd <- merge(ds, dfcastn,all= 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(yt) # fit arima model 
yfor <- forecast(yfit) # forecast 
pd <- funggcast(myts, yfor) # extract the data for ggplot using function funggcast() 

plotData<-ggplot(data = pd, aes(x = date, y = observed)) + geom_line(aes(color = "1")) + 
     geom_line(aes(y = fitted,color="2")) + 
     geom_line(aes(y = forecast,color="3")) + 
     scale_colour_manual(values=c("red", "blue","black"),labels = c("Observed", "Fitted", "Forecasted"),name="Data")+ 
     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)) + 
     ggtitle("Arima(0,1,1) Fit and Forecast of GDP per capita for Brazil (1960-2013)") 

plotData 

그리고 당신은 다음과 같습니다 플롯을 얻을 피팅은 완전히 무작위 시계열 꽤 나쁘다. 또한 ggplot은 2013 년 이전에 예측 라인에 데이터가 없기 때문에 몇 가지 오류를 출력합니다. 2013 년 이후에는 해당 데이터가 적용되지 않습니다. (초기 런 타임 시리즈에 따라 모델을 여러 번 실행했는데 모델이 어디에서나 0을 예측할 수 있습니다)

enter image description here

편집 : 나는 확실히 전설을 만들기 위해 코드의 끝에서 ggplot 기능을 변경 : 경우에는 관찰 된 데이터 2013

Edit2가 뒤에있다,뿐만 아니라 pd 할당 라인을 변경 위로 나타납니다

+0

가 귀하의 회신, 좋은 감사합니다! 나는 하나의 후속 질문이있다. 내 데이터는 사실 무작위가 아니며 54 건의 관측 (1960 년에서 2013 년까지)으로 구성됩니다 (ggtitle 참조). 따라서 나는 고의적으로'myts '를 연장 할 수 없다. 어쨌든 'myts'보다 어차피 그렇게하는 것은 시작부터 반복되는 관찰을 반복합니다. 어떻게 이것을 피할 수 있습니까? 'NA' 삽입!? 또는 다른 말로하면 (그래프를 보면) : 빨간색 선이 회색 영역을 벗어나는 것을 어떻게 피할 수 있습니까? –

+1

'pd' 할당 라인과'myts' 설명을 편집하여 여러분이 작성한'경고 '를 얻었습니다. 왜냐하면 2013 년이 훈련 시리즈의 끝이고 2023 년까지 예측하기 때문에'en'은 2023입니다 .최종 데이터 프레임에서 2013 년 이후에 관찰 된 값과 맞는 값에 대해 NAs가 자동으로 추가됩니다. – NicE

+0

빠른 편집을 해주셔서 감사합니다. 새로운'pd '할당을 나타낼 수 있습니까? 코드에서 찾을 수 없습니다!? –

2

ggfort라는 패키지가 있습니다. ggplot2를 사용하여 예측 객체를 곧바로 플로팅 할 수있는 github를 통해 사용할 수 있습니다. http://rpubs.com/sinhrks/plot_ts에서 찾을 수 있습니다.

0

이것은 다소 오래된 게시물의 범프이지만, 좋은 결과를 산출하는 fuction in github이 있습니다. 이 2016년 8월 3일에 있던으로

여기에 코드입니다 :

function(forec.obj, data.color = 'blue', fit.color = 'red', forec.color = 'black', 
          lower.fill = 'darkgrey', upper.fill = 'grey', format.date = F) 
{ 
    serie.orig = forec.obj$x 
    serie.fit = forec.obj$fitted 
    pi.strings = paste(forec.obj$level, '%', sep = '') 

    if(format.date) 
     dates = as.Date(time(serie.orig)) 
    else 
     dates = time(serie.orig) 

    serie.df = data.frame(date = dates, serie.orig = serie.orig, serie.fit = serie.fit) 

    forec.M = cbind(forec.obj$mean, forec.obj$lower[, 1:2], forec.obj$upper[, 1:2]) 
    forec.df = as.data.frame(forec.M) 
    colnames(forec.df) = c('forec.val', 'l0', 'l1', 'u0', 'u1') 

    if(format.date) 
     forec.df$date = as.Date(time(forec.obj$mean)) 
    else 
     forec.df$date = time(forec.obj$mean) 

    p = ggplot() + 
     geom_line(aes(date, serie.orig, colour = 'data'), data = serie.df) + 
     geom_line(aes(date, serie.fit, colour = 'fit'), data = serie.df) + 
     scale_y_continuous() + 
     geom_ribbon(aes(x = date, ymin = l0, ymax = u0, fill = 'lower'), data = forec.df, alpha = I(0.4)) + 
     geom_ribbon(aes(x = date, ymin = l1, ymax = u1, fill = 'upper'), data = forec.df, alpha = I(0.3)) + 
     geom_line(aes(date, forec.val, colour = 'forecast'), data = forec.df) + 
     scale_color_manual('Series', values=c('data' = data.color, 'fit' = fit.color, 'forecast' = forec.color)) + 
     scale_fill_manual('P.I.', values=c('lower' = lower.fill, 'upper' = upper.fill)) 

    if (format.date) 
     p = p + scale_x_date() 

    p 
}