如何使用循环基于长数据框在ggplot2中批量绘制多个箱线图并保存
R实现长数据按分析物分组批量生成箱线图并保存的方案
基础循环实现(易理解)
首先加载依赖包:
library(ggplot2) library(dplyr)
随后执行批量生成逻辑:
# 获取所有唯一的分析物名称 analyte_all <- unique(df$Analyte) # 遍历每个分析物生成图表 for (cur_analyte in analyte_all) { # 筛选当前分析物的子集数据 plot_data <- df %>% filter(Analyte == cur_analyte) # 生成箱线图 p <- ggplot(plot_data, aes(x = FY, y = Value)) + geom_boxplot() + labs( x = "财年", y = cur_analyte, # 动态设置Y轴标题为当前分析物名称 title = paste0(cur_analyte, " 各财年分布箱线图") ) + theme_bw() # 可选,优化图表样式 # 保存图表到工作目录,文件名包含分析物名称避免覆盖 png( filename = paste0("箱线图_", gsub("[^a-zA-Z0-9]", "_", cur_analyte), ".png"), width = 8, height = 6, units = "in", res = 150 ) print(p) dev.off() }
purrr函数式实现(更简洁)
如果习惯tidyverse的函数式写法,可以用purrr::walk实现,代码更简洁:
library(purrr) unique(df$Analyte) %>% walk(function(cur_analyte) { p <- df %>% filter(Analyte == cur_analyte) %>% ggplot(aes(x = FY, y = Value)) + geom_boxplot() + labs(x = "财年", y = cur_analyte) + theme_bw() ggsave( filename = paste0("箱线图_", gsub("[^a-zA-Z0-9]", "_", cur_analyte), ".png"), plot = p, width = 8, height = 6, dpi = 150 ) })
注意事项
- 代码中用
gsub处理分析物名称里的特殊字符,避免因为非法字符导致文件保存失败 - 如果财年
FY的展示顺序不对,可以先执行df$FY <- factor(df$FY, levels = sort(unique(df$FY)))固定时间顺序 - 可以根据需要调整
png/ggsave的宽高、分辨率参数,修改图片尺寸和清晰度
内容的提问来源于stack exchange,提问作者tm95
相关产品推荐
相关产品推荐

