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

如何用ggplot2修改checkresiduals绘图的轴名并移除标题

问题

用户通过以下R代码生成残差图:

## simulate ARIMA(1,0, 0)
set.seed(1)
ar1 <- arima.sim(n = 20, model = list(ar = 0.8, order = c(1, 0, 0)), sd = 1)
## do the plot
forecast::checkresiduals(forecast::auto.arima(ar1), main = "")

需要实现以下修改:

  • 移除图中自动生成的标题“Residual from ARIMA(2,0,0) with zero mean”
  • 将y轴标签df$y替换为value
  • 必须使用ggplot2包实现
解决方案

forecast::checkresiduals()默认输出基础绘图系统的组合图,要改用ggplot2实现,需先提取残差数据,分别绘制三个子图后再组合。具体代码如下:

library(forecast)
library(ggplot2)
library(gridExtra)

# 模拟数据并拟合ARIMA模型
set.seed(1)
ar1 <- arima.sim(n = 20, model = list(ar = 0.8, order = c(1, 0, 0)), sd = 1)
fit_model <- auto.arima(ar1)

# 提取残差并整理为数据框
residual_data <- data.frame(
  time_index = seq_along(residuals(fit_model)),
  value = residuals(fit_model)
)

# 1. 残差时序图
plot_resid_ts <- ggplot(residual_data, aes(x = time_index, y = value)) +
  geom_line(linewidth = 0.8) +
  geom_point(size = 2) +
  labs(x = "Index", y = "value") +
  theme_bw()

# 2. 残差直方图(带密度曲线)
plot_resid_hist <- ggplot(residual_data, aes(x = value)) +
  geom_histogram(aes(y = after_stat(density)), bins = 6, fill = "#69b3a2", color = "white") +
  geom_density(color = "#ff7f0e", linewidth = 1) +
  labs(x = "value", y = "Density") +
  theme_bw()

# 3. 残差QQ图
plot_resid_qq <- ggplot(residual_data, aes(sample = value)) +
  stat_qq(size = 2) +
  stat_qq_line(color = "#ff7f0e", linewidth = 1) +
  labs(x = "Theoretical Quantiles", y = "Sample Quantiles") +
  theme_bw()

# 组合三个子图
grid.arrange(plot_resid_ts, plot_resid_hist, plot_resid_qq, ncol = 3)

说明

  • 提取模型残差后整理成数据框,让ggplot2可以直接调用变量
  • 三个子图分别对应checkresiduals()的输出内容,全程没有自动生成的标题
  • 时序图的y轴直接设置为value,完全符合需求
  • 使用gridExtra::grid.arrange()实现多图布局,还原原函数的展示效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 13:45:32