【问题标题】:R: How to fill area between these two dashed linesR:如何填充这两条虚线之间的区域
【发布时间】:2020-05-22 15:16:18
【问题描述】:

我的名字是 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)

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

【问题讨论】:

  • 确保将dput(object) 的输出以及您正在使用的任何库添加到您的问题中

标签: r ggplot2 plot forecasting confidence-interval


【解决方案1】:

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

如果你有这样的数据

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

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

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

要获取 x 值,stats:::lines.ts 中使用的是 time(ts),其中 ts 是您的每个 upconfint 和 lowconfint。

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

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)

【讨论】:

  • 谢谢!这实际上回答了我的困惑,因为 x 轴是时间点,我不知道如何将其作为多边形函数的输入返回
猜你喜欢
  • 2020-07-12
  • 1970-01-01
  • 2023-03-22
  • 2017-11-09
  • 1970-01-01
  • 1970-01-01
  • 2020-01-18
  • 2013-11-07
  • 1970-01-01
相关资源
最近更新 更多