使用fpp3包复现ARIMA预测分位数可视化图表
用fpp3复现分位数预测图表
我之前用forecast包写了一段能生成美观分位数预测图的代码:
library(forecast) fit <- auto.arima(WWWusage) fc <- forecast(fit, h=20, level=95) qf <- matrix(0, nrow=99, ncol=20) m <- fc$mean s <- (fc$upper-fc$lower)/1.96/2 for(h in 1:20) qf[,h] <- qnorm((1:99)/100, m[h], s[h]) plot(fc) matlines(101:120, t(qf), col=rainbow(120), lty=1)
现在我用fpp3包处理另一个数据集,已经算出了预测分位数,但不知道怎么复现上面的图表:
library(fpp3) library(distributional) fc <- aus_production |> model(ARIMA(Beer)) |> forecast(h = 20) pc <- seq(99) fc |> as_tibble() |> group_by(Quarter) |> reframe(percentile = quantile(Beer, pc / 100)) |> unnest(percentile) |> mutate(pc = rep(pc, 20))
解决方案
结合fpp3和ggplot2的绘图能力,就能复现原图表效果,完整代码如下:
library(fpp3) library(distributional) library(ggplot2) # 生成预测结果 fc <- aus_production |> model(ARIMA(Beer)) |> forecast(h = 20) # 计算并整理分位数数据 pc <- seq(99) quantile_data <- fc |> as_tibble() |> group_by(Quarter) |> reframe(percentile = quantile(Beer, pc / 100)) |> unnest(percentile) |> mutate(pc = rep(pc, 20)) # 绘制基础预测图 + 叠加分位数线条 fc |> autoplot(aus_production) + theme_minimal() + geom_line( data = quantile_data, aes(x = Quarter, y = percentile, color = pc), linetype = 1 ) + scale_color_gradientn(colors = rainbow(120)) + guides(color = "none")
关键说明
autoplot(fc, aus_production):生成包含历史数据、预测均值和置信区间的基础图表,对应原代码的plot(fc)geom_line:遍历所有分位数,在对应时间点绘制线条scale_color_gradientn(colors = rainbow(120)):设置和原代码一致的彩虹色渐变效果guides(color = "none"):隐藏颜色图例,保持图表简洁度
内容的提问来源于stack exchange,提问作者lucamartono2
相关产品推荐
相关产品推荐

