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

如何将R语言ggpubr绘制的多个图表合并展示在同一画布中

解决方案

你已经引入了ggpubr包,直接使用包内置的ggarrange()函数即可实现多图拼接,还支持统一调整图例、添加子图序号等需求。我们可以先把重复的绘图逻辑封装为函数减少冗余代码,再将生成的4个图对象合并到同一张画布:

library(ggpubr)
library(rstatix)
library(xlsx)

# 读取数据
df <- read.xlsx("umar.xlsx", header = T, 1)

# 封装绘图函数,传入要绘制的y轴指标列名即可生成对应带显著性的箱线图
generate_bxp <- function(y_col){
  # 统计检验
  stat.test <- df %>%
    t_test(as.formula(paste0(y_col, "~ substrate"))) %>%
    add_significance()
  # 绘制箱线图
  bxp <- ggboxplot(df, x = "substrate", y = y_col, fill = "substrate", 
                   palette = c("#00AFBB", "#E7B800"), width = 0.35)
  # 添加显著性标记
  stat.test <- stat.test %>% add_xy_position(x = "substrate")
  bxp <- bxp + 
    stat_pvalue_manual(stat.test, label = "p = {p}") +
    scale_y_continuous(expand = expansion(mult = c(0.05, 0.1)))+
    theme(
      aspect.ratio = 3
    )
  return(bxp)
}

# 生成4个独立图对象
p1 <- generate_bxp("Moisture_content")
p2 <- generate_bxp("pH")
p3 <- generate_bxp("EC")
# 注意原代码中第4张图仍用了Moisture_content,可替换为你实际需要的第4个指标
p4 <- generate_bxp("Moisture_content")

# 合并4张图为2行2列布局
combined_plot <- ggarrange(
  p1, p2, p3, p4,
  nrow = 2,  # 行数
  ncol = 2,  # 列数
  common.legend = TRUE,  # 共用同一个图例(4个图分组规则一致可开启)
  legend = "bottom",  # 图例位置
  labels = c("A", "B", "C", "D")  # 子图左上角序号标签
)

# 查看合并后的图
print(combined_plot)

# 如需导出可直接用ggsave保存合并后的图
# ggsave("combined_boxplot.png", combined_plot, width = 10, height = 12, dpi = 300)
  • 可以根据需要调整nrow和ncol参数修改布局,比如想要1行4列就设置nrow=1, ncol=4
  • 如果不需要共用图例,把common.legend参数改为FALSE即可
  • labels参数支持自定义子图标签,也可以设置为"auto"自动生成大写字母序号

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:57:03