R语言循环绘图生成空白PDF,单独运行循环内代码功能正常
问题原因与解决方案
核心触发原因
R环境中,交互式执行代码时会自动打印绘图函数返回的绘图对象、完成图形渲染;但在循环体内执行时不会触发自动打印逻辑,绘图结果无法写入打开的PDF设备,最终生成空白PDF文件,完全匹配「单步执行正常、循环执行空白」的特征。
修复方案
按以下规则修改代码即可:
- 所有绘图语句外层包裹
print()强制渲染 - 循环执行前先创建输出目录,避免路径不存在导致写入失败
- 循环开头关闭残留的绘图设备,避免状态异常
修改后代码
# 提前创建输出目录 dir.create("results/out_of_sample", recursive = TRUE, showWarnings = FALSE) # 关闭所有残留绘图设备 graphics.off() for (garch_model_name in c('sGARCH', 'eGARCH', 'gjrGARCH')) { dist = 'jsu' p = 1 q = 1 print(garch_model_name) roll = list('start'=N, 'window'='expanding', 'k'=1) res = fit_GARCH(ret_d, resample=list(period='days', k=1), garchModel=garch_model_name, garchOrder=c(q,p), distModel=dist, roll=roll) spec = res$model mod = res$fit df = mod@forecast$density xdf = as.xts(df) tzone(xdf) = 'UTC' predictions = xdf$Sigma predictions_list[[garch_model_name]] = predictions realized = tail(RV, M) rmse_list[[garch_model_name]] = calc_rmse(predictions, realized) mae_list[[garch_model_name]] = calc_mae(predictions, realized) rmedse_list[[garch_model_name]] = sqrt(median((realized - predictions)^2)) mape_list[[garch_model_name]] = mean(abs((realized - predictions)/realized)) mz = lm(realized ~ predictions) s = summary(mz) mz_list[[garch_model_name]] = s$r.squared df = cbind(realized, predictions) colnames(df) = c('Realized', 'Forecast') pdf(file=sprintf('results/out_of_sample/realized_predicted_%s.pdf', garch_model_name)) # 新增print强制渲染 print(plot.xts(df, main='Realized vs Forecast', legend.loc='topright', col=c('black', 'red'), lty=c(1,1), lwd=c(1,2))) dev.off() errors = (realized - predictions)/realized * 100 pdf(file=sprintf('results/out_of_sample/forecast_errors_%s.pdf', garch_model_name)) # 新增print强制渲染 print(plot(errors, main=garch_model_name, ylab='% error')) dev.off() }
内容的提问来源于stack exchange,提问作者s5s
相关产品推荐
相关产品推荐

