R:如何填充这两条虚线之间的区域

R: How to fill area between these two dashed lines

我叫 Ihsan,如果我的英语听不懂,请见谅,

我需要帮助来创建阴影或填充这两条虚线之间的区域作为我的预测 "interval"

我的数据是(作为 ts 对象):

ts
     Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2018   0 208 112  39  65  38  17  54 105   0  66  24
2019   0   0  69 421   0   0   0   0   0   0   0  10

我的代码是:

library('tsintermittent')

ts <- structure(
  c(0L, 208L, 112L, 39L, 65L, 38L, 17L, 54L, 105L, 0L, 66L, 24L,
    0L, 0L, 69L, 421L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 10L),
  .Tsp = c(2018, 2019 + 11/12, 12), class = 'ts'
)

crost.frc <- crost(ts,h=3,w=NULL,init="mean",nop=1,type="croston",
                   cost=c("mae","mse"),init.opt = F,
                   outplot = F,opt.on = F,na.rm = F)

tsobj <- ts(c(ts,rep(NA,3)),frequency=12,start=c(2018,1))

fit <- ts(crost.frc$frc.in,frequency=12,start=c(2018,1))

y <- ts(c(fit,crost.frc$frc.out),frequency=12,start=c(2018,1))

upconfint <- ts(c(rep(NA,23),fit[24],y[25:27]+1.96*sd(ts-na.omit(fit))),
                frequency=12,start=c(2018,1))
lowconfint <- ts(c(rep(NA,23),fit[24],y[25:27]-1.96*sd(ts-na.omit(fit))),
                frequency=12,start=c(2018,1))

#Plot Forecast - Croston
plot(tsobj,pch=16,type="o",main="Metode Croston",xlab="Periode",ylab="Demand")

points(y,pch=1,type="o",col="purple")

points(upconfint,type="l",lty=3,col="grey",lwd=2)
points(lowconfint,type="l",lty=3,col="grey",lwd=2)

points(fit,pch=1,type="o",col="red")

legend("topleft", legend=c("Aktual","Fit","Forecast","Interval"),
       col=c("black","red","purple","grey"), lty=c(1,1,1,2), cex=0.8)

非常期待您的建议,谢谢!

我从不使用时间序列,所以这可能是一个困难的方法。

如果你有这样的数据

x <- 1:5
y <- 1:5

那么您对 ​​polygon 的调用应该如下所示

polygon(c(x, rev(x)), c(y, rev(y)))

要获得 x 值,stats:::lines.ts 中使用的是 time(ts),其中 ts 是您的 upconfintlowconfint

但是如果你想在其他部分下绘制置信区间,你将不得不重新排序你的绘图:

plot(tsobj,pch=16,type="o",main="Metode Croston",xlab="Periode",ylab="Demand")

xx <- c(time(upconfint), rev(time(lowconfint)))
yy <- c(upconfint, rev(lowconfint))
polygon(xx, yy, col = 'grey95', border = NA)

points(upconfint,type="l",lty=3,col="grey",lwd=2)
points(lowconfint,type="l",lty=3,col="grey",lwd=2)

points(y,pch=1,type="o",col="purple")
points(fit,pch=1,type="o",col="red")

legend("topleft", legend=c("Aktual","Fit","Forecast","Interval"),
       col=c("black","red","purple","grey"), lty=c(1,1,1,2), cex=0.8)