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

如何在R脚本中保存easystats check_model生成的诊断图?

如何保存easystats::check_model生成的诊断图

更新easystats后原保存方法失效,核心原因是check_model()返回的对象结构发生了变化:现在它要么是自定义的check_model类对象,要么调用plot()后返回多个ggplot子图组成的列表,而ggsave仅能直接处理单个ggplot对象,因此触发报错。

下面提供三种可行的解决方法:

方法1:合并子图后保存

plot(check_model(model))会返回包含所有诊断子图的列表,用see::plot_grid()将它们合并为一个完整的绘图对象,再用ggsave保存:

# 生成诊断子图列表
diagnost_plots <- plot(check_model(model))
# 合并子图
combined_plot <- see::plot_grid(plotlist = diagnost_plots)
# 保存(可按需调整尺寸)
ggsave(diagnostic_path, plot = combined_plot, width = 12, height = 8)

方法2:直接用check_model的save参数

最新版本的check_model内置了保存功能,只需指定save参数即可一步完成生成和保存,无需额外调用ggsave:

check_model(model, save = diagnostic_path, width = 12, height = 8)

方法3:通过设备捕获绘图

如果前两种方法不适用,可以直接打开绘图设备,打印check_model对象后关闭设备实现保存:

png(diagnostic_path, width = 1200, height = 800)
print(check_model(model))
dev.off()

完整可运行示例

将上述方法整合到循环脚本中:

rm(list = ls())
graphics.off()

library(lme4)
library(ggplot2)
library(easystats)
library(see)

# 构建示例数据
n_groups = 2
time_points = c(1,5,9,12)
n_subjects = 8
n_variables = 2

data = expand.grid(group = paste0("Group",1:n_groups), time = time_points, subject = 1:n_subjects)
data = data[order(data$group, data$time, data$subject), ]
for (i in 1:n_variables) {data[[paste0("var", i)]] <- rnorm(nrow(data))}

# 循环处理变量
for (variable in paste0("var", 1:n_variables)) {
  model = lmer(data[[variable]] ~ time*group + (1 + time | subject), data, control = lmerControl(optimizer="Nelder_Mead"))

  boxplot_path = paste0("Example_Boxplot_", variable, ".png")
  diagnostic_path = paste0("Example_Diagnostic_", variable, ".png")
  
  # 保存箱线图
  variable_boxplot = ggplot(data, 
                          aes(x = time, 
                          y = !!sym(variable), 
                          group = interaction(time, group),
                          fill = group)) +
                    geom_boxplot(width = 3, 
                          position = position_dodge(width = 1.5),
                          alpha = 0.6)
  ggsave(boxplot_path, plot = variable_boxplot)

  # 使用方法1保存诊断图
  diagnost_plots <- plot(check_model(model))
  combined_plot <- see::plot_grid(plotlist = diagnost_plots)
  ggsave(diagnostic_path, plot = combined_plot, width = 12, height = 8)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 14:32:03