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

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

我的名字叫Ihsan,如果无法理解,请为我的英语感到抱歉,

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

“

我的数据是(作为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)

我真的很期待您的建议,谢谢!

r ggplot2 plot forecasting confidence-interval
1个回答
0
投票

我从不使用时间序列,所以这可能很难。

如果您有这样的数据

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)

enter image description here

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