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

使用funggcast函数在ggplot绘制时间序列时遇日期转换错误

问题解决:时间序列转Date类型错误及ggplot绘图修正

错误原因

你的时间序列是年度频率(freq=1),time()函数返回的是数值型年份(如1980、1981),而as.Date()无法直接将纯数值年份转换为日期类,必须先拼接成标准日期字符串(比如"1980-01-01")才能完成转换。

修改后的完整代码

以下是修正funggcast函数日期转换逻辑、同时更新ggplot2旧语法后的可运行代码:

#----------模拟Arima(3, 1, 4)时间序列-------------
library(forecast)
library(ggplot2)
library(scales)

y <- arima.sim(model=list(order=c(3, 1, 4),ar=c(0.7662, 0.8768, - 0.7183), ma = c(- 0.0256, - 0.9333, 0.0041, - 0.0207)),n = 42)
y <- ts(y,freq=1,start=c(1980))

#-- 提取训练数据、拟合模型并生成预测
yt <- window(y, end=2020)
yfit <- Arima(yt, order=c(3, 1, 4))
yfor <- forecast(yfit)

#---修正后的funggcast函数---
funggcast <- function(dn, fcast){
  
  en <- max(time(fcast$mean)) 
  
  # 处理观测数据:数值年份转成"YYYY-01-01"格式的日期
  ds <- as.data.frame(window(dn, end = en))
  names(ds) <- 'observed'
  ds$date <- as.Date(paste(time(window(dn, end = en)), "01", "01", sep = "-"))
  
  # 处理拟合值的日期
  dfit <- as.data.frame(fcast$fitted)
  dfit$date <- as.Date(paste(time(fcast$fitted), "01", "01", sep = "-"))
  names(dfit)[1] <- 'fitted'
  
  ds <- merge(ds, dfit, all.x = T) 
  
  # 处理预测值的日期
  dfcastn <- as.data.frame(fcast)
  dfcastn$date <- as.Date(paste(row.names(dfcastn),"01","01",sep="-"))
  names(dfcastn) <- c('forecast','lo80','hi80','lo95','hi95','date')
  
  pd <- merge(ds, dfcastn, all= T) 
  return(pd)
  
} 

pd <- funggcast(y,yfor)

#---修改后的ggplot绘图代码---
p1a <- ggplot(data=pd,aes(x=date,y=observed)) +
  geom_line(col='red') +
  geom_line(aes(y=fitted),col='blue') +
  geom_line(aes(y=forecast)) +
  geom_ribbon(aes(ymin=lo95,ymax=hi95), alpha=.25) +
  scale_x_date(name='', breaks='1 year', minor_breaks='1 month', 
               labels=date_format("%b-%y"), expand=c(0,0)) +
  scale_y_continuous(name='Units of Y') +
  theme(axis.text.x = element_text(size=10),
        plot.title = element_text(hjust = 0.5)) +
  labs(title='Arima Fit to Simulated Data\n(black=forecast, blue=fitted, red=data, shadow=95% conf. interval)')

# 展示绘图
print(p1a)

关键修改点

  • 将所有as.Date(time(...))替换为as.Date(paste(time(...), "01", "01", sep = "-")),把数值年份转成标准的年初日期格式
  • 替换ggplot2中已弃用的opts()为theme(),theme_text()为element_text()
  • 用labs()统一设置标题,并添加居中对齐逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 19:44:53