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

如何从R语言tsdiag函数输出的3张诊断图中单独提取保存一张?

单张提取tsdiag诊断图的实现方法

R 原生 stats 包提供的 tsdiag 系列方法默认没有内置 which 参数,你尝试传入该参数不会生效,函数始终输出全部3张诊断图,分别为:标准化残差时序图、残差ACF图、Ljung-Box检验p值图。
tsdiag诊断图示例

以下是两种可行的实现方案:

方案1:单独绘制目标诊断图

直接手动绘制你需要的单张图,完全跳过tsdiag封装,灵活性最高:

  • 提取第1张(标准化残差时序图):
# 保存到本地示例
png("standard_residuals.png", width = 600, height = 400)
plot(rstandard(arima_model), main = "Standardized Residuals")
dev.off()
  • 提取第2张(残差ACF图):
png("residual_acf.png", width = 600, height = 400)
acf(residuals(arima_model), na.action = na.pass, main = "ACF of Residuals")
dev.off()
  • 提取第3张(Ljung-Box检验p值图):
png("ljung_box_p.png", width = 600, height = 400)
nlag <- 20 # 和tsdiag默认滞后阶数一致
pvals <- sapply(1:nlag, function(k) Box.test(resid(arima_model), lag=k, type="Ljung-Box")$p.value)
plot(1:nlag, pvals, ylim=c(0,1), xlab="Lag", ylab="p value", main="p values for Ljung-Box statistic")
abline(h=0.05, lty=2, col="red")
dev.off()

方案2:改写tsdiag函数增加which参数

如果你需要保留tsdiag的原生绘图样式,可以直接修改函数源码增加参数控制:

# 改写Arima模型对应的tsdiag方法,增加which参数
tsdiag_custom <- function(object, which = 1:3, gof.lag = 10, ...) {
  rs <- rstandard(object)
  if (1 %in% which) {
    plot(rs, ylab = "Standardized Residuals", main = "")
    abline(h = 0, lty = 3)
  }
  if (2 %in% which) {
    acf(resid(object), na.action = na.pass, lag.max = gof.lag, main = "")
  }
  if (3 %in% which) {
    pval <- sapply(1:gof.lag, function(i) Box.test(resid(object), lag = i, type = "Ljung-Box")$p.value)
    plot(1:gof.lag, pval, xlab = "Lag", ylab = "p-value", ylim = c(0, 1), main = "")
    abline(h = 0.05, lty = 2, col = "red")
  }
}

# 调用示例:仅输出第1张图保存
png("custom_tsdiag.png", width = 600, height = 400)
tsdiag_custom(arima_model, which = 1)
dev.off()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 04:36:03