这是一个小例子。但是,它必须通过循环分段 ( 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")