如何将forecast包checkresiduals生成的分面图转为可调用ggplot2对象
复刻checkresiduals的可调用ggplot2对象
要把checkresiduals()生成的残差分面图转化为可后续调用的ggplot2对象,你需要手动提取残差数据,用ggplot2分别绘制三个子图后拼接,具体步骤如下:
1. 准备环境与提取残差数据
先确保所需包已安装加载,再从预测对象中提取残差并整理为数据框:
# 如果未安装patchwork包,先执行安装 # install.packages("patchwork") library(fabletools) library(forecast) library(ggplot2) library(patchwork) # 生成预测对象 Test_plt <- fdeaths %>% forecast() # 提取残差并转为带时间索引的数据框 resid_df <- data.frame( time = time(residuals(Test_plt)), resid = as.numeric(residuals(Test_plt)) )
2. 复刻三个子图
checkresiduals()默认生成三个面板,我们逐个用ggplot2实现:
残差时间序列图
p1 <- ggplot(resid_df, aes(x = time, y = resid)) + geom_line(color = "#0072B2") + geom_hline(yintercept = 0, linetype = "dashed", color = "#D55E00") + labs(x = "时间", y = "残差", title = "残差时间序列") + theme_minimal()
残差直方图+密度曲线
p2 <- ggplot(resid_df, aes(x = resid)) + geom_histogram(aes(y = after_stat(density)), bins = 15, fill = "#0072B2", alpha = 0.7) + geom_density(color = "#D55E00", linewidth = 1) + labs(x = "残差", y = "密度", title = "残差分布") + theme_minimal()
残差QQ图
p3 <- ggplot(resid_df, aes(sample = resid)) + stat_qq(color = "#0072B2") + stat_qq_line(color = "#D55E00", linewidth = 1) + labs(x = "理论分位数", y = "样本分位数", title = "QQ图") + theme_minimal()
3. 拼接为分面布局
用patchwork复刻原函数的2行1列布局:
# 拼接成最终可调用的ggplot2对象 residual_plot <- (p1 + p2) / p3 + plot_layout(heights = c(1, 1)) # 调用图形对象查看 residual_plot
生成的residual_plot是标准ggplot2对象,后续可随时调用、修改主题或添加元素。若需保留原函数的Ljung-Box检验结果,可单独提取:
lb_test <- checkresiduals(Test_plt) # 查看检验结果 lb_test
内容的提问来源于stack exchange,提问作者silent_hunter
相关产品推荐
相关产品推荐

