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

4

1 回答 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")

在此处输入图像描述

于 2019-04-23T14:17:08.053 回答