我正在使用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
发布于 2019-04-23 22:17:08
这里有一个小例子。但是,它必须自动循环绘制线段(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")

https://stackoverflow.com/questions/55497557
复制相似问题