如何在R的fable包中按分组批量生成单独预测图并保存?
批量生成fable预测图(按都市区拆分并保存PDF)
问题场景
使用R的fable包完成都市区预测后,希望为64个都市区单独生成预测图(而非用facet_wrap合并展示),但执行以下代码时出现错误:
forecastplots <- forecasts %>% group_by(Metro) %>% autoplot(fabledata)
错误信息
Error in `hilo()`: ! Objects of type `grouped_ts` are not supported by `hilo()`, you can create a custom `hilo` with `new_hilo()` • Objects of type `grouped_df` are not supported by `hilo()`, you can create a custom `hilo` with `new_hilo()` • Objects of type `tbl_ts` are not supported by `hilo()`, you can create a custom `hilo` with `new_hilo()` • Objects of type `tbl_df` are not supported by `hilo()`, you can create a custom `hilo` with `new_hilo()` • Objects of type `tbl` are not supported by `hilo()`, you can create a custom `hilo` with `new_hilo()` • Objects of type `data.frame` are not supported by `hilo()`, you can create a custom `hilo` with `new_hilo()` Run `rlang::last_error()` to see where the error occurred.
错误核心:group_by()生成的分组对象(grouped_ts)无法被autoplot.fable依赖的hilo()函数处理,必须将每个都市区的预测数据单独拆分后再绘图。
解决方案:批量生成并保存到PDF
无需逐个手动筛选都市区,用dplyr+purrr的组合即可实现自动化批量处理,以下提供两种可行方法:
方法1:用group_split拆分后遍历绘图
library(fable) library(tsibble) library(dplyr) library(purrr) library(ggplot2) # 1. 按Metro字段拆分预测数据,得到每个都市区的独立数据集 metro_forecast_list <- forecasts %>% group_split(Metro, .keep = TRUE) # 2. 遍历生成每个都市区的预测图,自动添加标题 metro_plot_list <- metro_forecast_list %>% map(function(metro_data) { autoplot(metro_data, fabledata) + labs(title = unique(metro_data$Metro), x = "时间", y = "预测值") + theme_minimal() }) # 3. 将所有图批量保存到单个PDF文件 pdf("所有都市区预测图.pdf", width = 10, height = 6) walk(metro_plot_list, print) # 逐个打印绘图对象到PDF dev.off()
方法2:用nest嵌套数据后生成图列
library(fable) library(tsibble) library(dplyr) library(purrr) library(ggplot2) # 1. 按Metro嵌套数据,生成包含每个都市区预测数据的列表列 nested_forecasts <- forecasts %>% nest(forecast_data = -Metro) # 2. 生成每个都市区的预测图,存储到新的plot列 nested_forecasts <- nested_forecasts %>% mutate(plot = map2(forecast_data, Metro, ~{ autoplot(.x, fabledata) + labs(title = .y, x = "时间", y = "预测值") + theme_minimal() })) # 3. 提取所有图并保存到PDF pdf("所有都市区预测图.pdf", width = 10, height = 6) walk(nested_forecasts$plot, print) dev.off()
内容的提问来源于stack exchange,提问作者John Meszaros
相关产品推荐
相关产品推荐

