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

R语言中如何让plot绘制的预测线与实际值首尾相连?

解决预测线与实际值不连接的问题

我帮你排查了代码和问题,主要有两个关键调整点可以解决这个问题:

1. 修正变量名错误

你的代码最后一行写的是plot(pronostico),但前面生成的预测对象是pred,变量名不匹配会导致无法正确绘制预测结果,先把这行改成plot(pred)。

2. 启用实际值与预测值的连接

forecast包的绘图函数默认不会连接历史数据和预测数据,只需要在plot()中添加connect = TRUE参数,就能让预测线从最后一个已知值无缝连接到第一个预测值。

修改后的完整代码

# Load Forecast library
library(forecast)
# Load dataset
bwi <- read.csv(file="C:/Users/nsoria/Downloads/AMS Globales/TEC_BWI.csv", header=TRUE, sep=';', dec=",")
# Create time series starting in January 2015
ts_bwi <- ts(bwi$BWI, frequency = 12, start = c(2015,1))
# Pull out the seasonal, trend, and irregular components from the time series
model <- stl(ts_bwi, s.window = "periodic")
# Predict the next 5 months of SLA
pred <- forecast(model, h = 5)
# Plot the results with connection between actual and predicted values
plot(pred, connect = TRUE)

备选方案(针对旧版本forecast包)

如果你的forecast版本较旧,connect参数无效,可以手动用lines()函数补充连接线:

# 先绘制基础预测图
plot(pred)
# 获取最后一个实际值和第一个预测值的数值与时间点
last_actual_val <- tail(ts_bwi, 1)
first_pred_val <- pred$mean[1]
last_actual_time <- time(ts_bwi)[length(ts_bwi)]
first_pred_time <- time(pred$mean)[1]
# 添加连接线
lines(x = c(last_actual_time, first_pred_time), y = c(last_actual_val, first_pred_val), col = "red", lwd = 1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:47:24