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

大数据集批量箱线图绘制:如何拆分生成280个单变量独立箱线图

R语言批量生成单变量分组箱线图解决方案

实现思路

遍历所有观测变量,对每个变量单独筛选数据绘图并自动保存,无需重复编写绘图代码。

前置准备

你已经完成宽表转长表的步骤,首先提取所有待绘图的唯一变量名,并创建存储图片的文件夹避免文件混乱:

# 提取所有唯一变量名
unique_vars <- unique(long_df$variable)
# 创建存储图片的文件夹,已存在时不会报错
dir.create("group_boxplots", showWarnings = FALSE)

方案1:基础R循环实现(易理解易调整)

library(ggplot2)

for (current_var in unique_vars) {
  # 筛选当前变量的分组数据
  sub_df <- long_df[long_df$variable == current_var, ]
  
  # 绘制分组箱线图
  p <- ggplot(sub_df, aes(x = group, y = value, fill = group)) +
    geom_boxplot() +
    labs(
      title = paste0(current_var, " 对照组与患者组分布对比"),
      x = "分组",
      y = current_var
    ) +
    theme_bw() # 可根据需要自定义主题、配色、坐标轴范围等
  
  # 自动处理文件名中的特殊符号(空格、%、单位等)避免保存失败
  file_name <- paste0("group_boxplots/", gsub("[^[:alnum:]]", "_", current_var), ".png")
  # 保存图片,可自定义尺寸、分辨率、输出格式(如jpg/pdf)
  ggsave(file_name, plot = p, width = 6, height = 4, dpi = 300)
}

方案2:tidyverse风格purrr包实现(代码更简洁)

library(ggplot2)
library(dplyr)
library(purrr)

# 定义单变量绘图函数
plot_single_var <- function(current_var) {
  p <- long_df %>%
    filter(variable == current_var) %>%
    ggplot(aes(x = group, y = value, fill = group)) +
    geom_boxplot() +
    labs(
      title = paste0(current_var, " 分组分布对比"),
      x = "分组",
      y = current_var
    ) +
    theme_bw()
  
  file_name <- paste0("group_boxplots/", gsub("[^[:alnum:]]", "_", current_var), ".png")
  ggsave(file_name, plot = p, width = 6, height = 4, dpi = 300)
}

# 批量执行绘图
walk(unique_vars, plot_single_var)

可选优化

  • 如果需要添加组间统计显著性标记,可在绘图代码中加入ggsignif包的geom_signif()层
  • 可通过调整ggsave的参数修改输出格式为矢量图(pdf/svg)、调整图片尺寸和分辨率
  • 若需要将多张图合并到同一个PDF的不同页面,可将所有绘图结果存在列表中后用ggsave直接保存列表到多页PDF

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:15:01