如何在R中按分组绘制预测与实际数据对比图表并保存
问题描述
现有两个数据集:
1. Forecast数据集
Forecast=structure(list(sub = c("01.01.01 Automatic switches ARMAT", "01.01.01 Automatic switches ARMAT", "01.01.01 Automatic switches ARMAT", "01.01.02 Automatic switches KARAT", "01.01.02 Automatic switches KARAT", "01.01.02 Automatic switches KARAT" ), ds = c("01.05.2022", "01.06.2022", "01.07.2022", "01.05.2022", "01.06.2022", "01.07.2022"), forecast = c(30696L, 30696L, 30696L, 1089910L, 1089910L, 1089910L), fct = c(22590L, 29243L, 30521L, 803535L, 1430316L, 1312260L)), class = "data.frame", row.names = c(NA, -6L))
其中sub为分组变量,forecast列是月度预测值,fct(实际值)列是实际数据,预测按sub分组单独执行。
2. manager_forecast数据集
manager_forecast=structure(list(sud = c("01.01.01 Automatic switches ARMAT", "01.01.01 Automatic switches ARMAT", "01.01.02 Automatic switches KARAT", "01.01.02 Automatic switches KARAT", "", ""), ds = c("01.06.2022", "01.07.2022", "01.06.2022", "01.07.2022", "", ""), manager_forecast = c(76011.04671, 113534.0746, 1802431.458, 1399089.059, NA, NA)), class = "data.frame", row.names = c(NA, -6L))
该数据集结构类似,manager_forecast列是经理预测的销量。
需求
按每个sub分组,绘制展示预测值、实际值、经理预测值相关性的对比图表(类似Excel趋势对比图),并将每个分组的图表保存至C:/1/plots文件夹,求最简实现方法。
最简实现方法(R语言)
步骤1:安装并加载必要工具包
install.packages(c("tidyverse", "lubridate")) library(tidyverse) library(lubridate)
步骤2:数据预处理与合并
修正manager_forecast的列名错误,清理无效空行,再与Forecast按分组和日期合并:
# 清理经理预测数据 manager_clean <- manager_forecast %>% rename(sub = sud) %>% filter(sub != "", !is.na(ds)) %>% mutate(ds = dmy(ds)) # 转换日期格式并合并两个数据集 combined_data <- Forecast %>% mutate(ds = dmy(ds)) %>% left_join(manager_clean, by = c("sub", "ds"))
步骤3:分组绘图并批量保存
按sub拆分数据,循环生成每个分组的趋势对比图并保存到指定路径:
# 自动创建保存目录(不存在则新建) dir.create("C:/1/plots", recursive = TRUE, showWarnings = FALSE) # 分组绘图+保存 combined_data %>% group_split(sub) %>% walk(function(df) { # 生成合法文件名(替换特殊字符) filename <- str_replace_all(df$sub[1], "[^a-zA-Z0-9]", "_") %>% paste0("C:/1/plots/", ., ".png") # 绘制折线+点的对比图 p <- ggplot(df, aes(x = ds)) + geom_line(aes(y = forecast, color = "模型预测值"), linewidth = 1) + geom_line(aes(y = fct, color = "实际值"), linewidth = 1) + geom_line(aes(y = manager_forecast, color = "经理预测值"), linewidth = 1, na.rm = TRUE) + geom_point(aes(y = forecast), color = "blue") + geom_point(aes(y = fct), color = "green") + geom_point(aes(y = manager_forecast), color = "red", na.rm = TRUE) + labs(title = unique(df$sub), x = "日期", y = "销量", color = "数据类型") + theme_minimal() + theme(plot.title = element_text(hjust = 0.5)) # 保存图表 ggsave(filename, p, width = 10, height = 6, dpi = 100) })
补充说明
- 图表类型:若需要柱状对比,可将
geom_line替换为geom_col,并添加position = "dodge"实现并列柱状。 - 空值处理:经理预测仅覆盖6、7月数据,绘图时用
na.rm=TRUE自动忽略空值,避免报错。 - 文件名适配:替换分组名称中的特殊字符为下划线,防止保存时出现路径错误。
内容的提问来源于stack exchange,提问作者psysky
相关产品推荐
相关产品推荐

