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

如何在ggplot2箱线图旁展示基本汇总统计量?

在ggplot2箱线图旁添加汇总统计量的实现方法

完全可以实现,以下是两种实用方案,基于你提供的数据集和基础代码修改:

方案一:直接在箱线图右侧添加统计量文本

无需额外依赖包,直接用annotate()在图中插入统计信息:

library(ggplot2)

# 整理统计量为带标签的文本向量
stats_text <- c(
  paste("最小值 (Min):", round(quarts$min, 2)),
  paste("第一四分位数 (Q1):", round(quarts$q1, 2)),
  paste("中位数 (Median):", round(quarts$median, 2)),
  paste("均值 (Mean):", round(quarts$mean, 2)),
  paste("第三四分位数 (Q3):", round(quarts$q3, 2)),
  paste("最大值 (Max):", round(quarts$max, 2)),
  paste("标准差 (Std Dev):", round(quarts$st_dev, 2)),
  paste("四分位距 (IQR):", round(quarts$iqr, 2))
)

# 绘制箱线图并添加统计文本
ggplot(throu, aes(y = throughput_time)) + 
  geom_boxplot(fill = "slateblue", alpha = 0.2, width = 0.05) +
  xlim(-0.1, 0.3) +  # 扩大x轴范围,为统计文本预留空间
  xlab("") + ylab("案例持续时间(天)") + 
  theme_classic() + 
  theme(axis.ticks.x = element_blank(), axis.text.x = element_blank()) +
  # 插入统计文本,调整位置和样式
  annotate("text", x = 0.15, y = seq(max(throu$throughput_time), max(throu$throughput_time)-30, length.out = 8),
           label = stats_text, hjust = 0, size = 3.5)

方案二:以表格形式展示统计量,与箱线图并排

需要gridExtra包,将箱线图和统计量表格放在同一画布:

library(ggplot2)
library(gridExtra)
library(grid)

# 转换统计量数据集为适合展示的格式
stats_table <- as.data.frame(t(quarts))
colnames(stats_table) <- "数值"
stats_table$统计量 <- rownames(stats_table)
stats_table <- stats_table[, c("统计量", "数值")]
stats_table$数值 <- round(stats_table$数值, 2)

# 绘制基础箱线图
box_plot <- ggplot(throu, aes(y = throughput_time)) + 
  geom_boxplot(fill = "slateblue", alpha = 0.2, width = 0.05) +
  xlim(-0.1, 0.1) +
  xlab("") + ylab("案例持续时间(天)") + 
  theme_classic() + 
  theme(axis.ticks.x = element_blank(), axis.text.x = element_blank())

# 绘制统计量表格
table_plot <- tableGrob(stats_table, rows = NULL, theme = ttheme_minimal(
  core = list(fg_params = list(size = 10)),
  colhead = list(fg_params = list(size = 11, fontface = "bold"))
))

# 组合箱线图与表格
grid.arrange(box_plot, table_plot, ncol = 2, widths = c(2, 1))

补充说明

  • 方案一适合紧凑展示场景,可通过调整x/y参数控制文本位置;
  • 方案二更清晰直观,适合完整呈现统计量的场景,可通过widths参数调整图与表格的宽度比例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 08:55:19