将ggfortify autoplot与changepoint包函数相结合(cpt.meanvar)

问题描述 投票:1回答:1

我在ggfortify包中使用autoplot函数来绘制具有预测和拟合的时间序列图,这是我如何做的

library(forecast)
library(ggplot2)
library(ggfortify)
fc <- forecast(fdeaths)
autoplot(fc)
autoplot(fc) + geom_line(aes(y = fitted(fc)), col = "red")

现在我想显示平均值发生变化的时间段以及变换前后的平均值,所有这些都在上图中

我可以使用'changepoint'包单独进行,语法如下

library(changepoint)
autoplot(cpt.mean(fdeaths))

plot(cpt.mean(fdeaths),cpt.col='blue')

所有这些的综合视图将提供非常强大的洞察力,请求帮助] 1

r ggplot2 forecast
1个回答
0
投票

这是一个小例子。但是,它必须自动化循环段(geom_segment)和vline(geom_vline)的图。

library(forecast)
library(ggplot2)
library(ggfortify)
library(changepoint)
library(lubridate)

fc <- forecast(fdeaths)
cp <- changepoint::cpt.mean(fdeaths)
plot(cp,cpt.col='blue')
# plot(x = 1:length(c(fdeaths)), y = c(fdeaths), type = "l")
Vikram <- data.frame(ts = c(fdeaths),
                     Obs = seq(lubridate::ymd('1974-01-01'),
                               lubridate::ymd('1979-12-01'), by = "1 month"),
                     fitted = fitted(fc))
Vikram_md <- changepoint::param.est(cp)[[1]] # mean
# cp@cpts  # change-points
cp_ <- cp@cpts

autoplot(fc) + geom_line(aes(y = fitted(fc)), col = "red") +
  geom_segment(x = Vikram$Obs[1], 
               y = Vikram_md[1], yend = Vikram_md[1],
               xend = Vikram$Obs[1] %m+% months(cp_[1]), 
               size = 1.2, col = "blue") +
  geom_segment(x = Vikram$Obs[1] %m+% months(cp_[1]), 
               y = Vikram_md[2], yend = Vikram_md[2],
               xend = Vikram$Obs[1] %m+% months(cp_[2]), 
               size = 1.2, col = "blue") +
  geom_vline(aes(xintercept = Vikram$Obs[1] %m+% months(cp_[2])),
             linetype = "dashed", colour = "red")

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.