You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将forecast包生成的图表转换为Plotly交互式图表?

解决forecast预测图转Plotly缺失置信区间的问题

问题原因

autoplot()生成的ggplot对象中,置信区间是通过*geom_ribbon*图层绘制的,但ggplotly()对这类自动生成的图层转换支持不完善,导致置信区间和预测线丢失。

解决方案

手动提取forecast对象的原始数据,重新构建ggplot图表后再转换为Plotly,就能完整保留所有元素:

library(fabletools)
library(forecast)
library(plotly)
library(ggplot2)

# 生成预测对象
fc <- fdeaths %>% forecast()

# 整理历史数据
hist_data <- data.frame(
  date = time(fdeaths),
  value = as.numeric(fdeaths),
  type = "历史数据"
)

# 整理预测数据(包含置信区间)
forecast_data <- data.frame(
  date = time(fc$mean),
  value = as.numeric(fc$mean),
  lower_80 = as.numeric(fc$lower[, "80%"]),
  upper_80 = as.numeric(fc$upper[, "80%"]),
  lower_95 = as.numeric(fc$lower[, "95%"]),
  upper_95 = as.numeric(fc$upper[, "95%"]),
  type = "预测数据"
)

# 手动构建ggplot图表
p <- ggplot() +
  # 绘制历史数据折线
  geom_line(data = hist_data, aes(x = date, y = value, color = type)) +
  # 绘制预测数据折线
  geom_line(data = forecast_data, aes(x = date, y = value, color = type)) +
  # 绘制95%置信区间
  geom_ribbon(data = forecast_data, aes(x = date, ymin = lower_95, ymax = upper_95), fill = "#1f77b4", alpha = 0.2) +
  # 绘制80%置信区间
  geom_ribbon(data = forecast_data, aes(x = date, ymin = lower_80, ymax = upper_80), fill = "#1f77b4", alpha = 0.3) +
  labs(x = "日期", y = "死亡人数", color = "数据类型") +
  theme_minimal()

# 转换为Plotly对象
ggplotly(p)

关键说明

  • 手动拆分历史数据与预测数据,明确定义每一个图层的数据源和映射关系,避免autoplot()生成的隐藏图层被ggplotly()忽略
  • 两层*geom_ribbon*分别对应95%和80%置信区间,通过不同的透明度区分层级
  • 转换后的Plotly图表会完整保留历史折线、预测折线以及两层置信区间

内容的提问来源于stack exchange,提问作者silent_hunter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 22:02:09