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

使用R语言mirt包时函数内保存绘图失败的问题排查

问题分析:mirt包trace图无法通过自定义函数保存

问题重现

自定义了保存基础绘图的函数save_as_file,测试基础绘图时能正常生成文件,但保存mirt包的trace图时,直接调用plot(mirt_fit, type="trace")可正常显示,用函数却无法生成对应图片文件。

相关代码:

# 保存基础绘图的自定义函数
save_as_file = function(code, filename, width = 1000, height = 750) {
  png(filename, width = width, height = height)
  eval(substitute(code))
  dev.off()
  try(dev.off(), silent = T)
}

# 基础绘图测试(正常工作)
plot(1:3)
save_as_file(plot(1:3), "test.png")
file.remove("test.png")

# mirt包测试(无法生成图片)
library(mirt)
set.seed(1)
mirt_data = mirt::simdata(
  a = c(1:4),
  d = c(0,0,1,1),
  N = 1000,
  itemtype = "2PL"
)
mirt_fit = mirt(
  data = mirt_data,
  model = 1,
  itemtype = "2PL",
  verbose = F
)
plot(mirt_fit, type = "trace") # 正常显示
save_as_file(plot(mirt_fit, type = "trace"), "mirt.png") # 无图片生成

原因解析

  • mirt包的plot()方法基于lattice绘图系统,而非R原生的基础绘图系统。
  • 基础绘图的plot()是直接在当前设备上绘制图形,无返回值;但lattice绘图会生成一个trellis对象,默认不会自动渲染到设备,必须显式调用print()才能触发绘图动作。
  • 自定义函数中eval(substitute(code))仅执行了plot(mirt_fit, type="trace"),创建了trellis对象但未打印,导致png设备中无内容,最终无法生成有效图片。而在控制台直接调用时,R会自动打印返回的对象,因此能正常显示。

解决方案

方案1:修改自定义函数,自动打印绘图对象

修改save_as_file函数,对eval的结果调用print(),确保lattice绘图被渲染到设备:

save_as_file = function(code, filename, width = 1000, height = 750) {
  png(filename, width = width, height = height)
  print(eval(substitute(code)))  # 新增print()触发渲染
  dev.off()
  try(dev.off(), silent = T)
}

调用方式不变:

save_as_file(plot(mirt_fit, type = "trace"), "mirt.png")

方案2:调用时手动显式打印

不修改函数,在传入的代码中直接添加print():

save_as_file(print(plot(mirt_fit, type = "trace")), "mirt.png")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 19:45:21