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

如何在Base R中为折线图添加基于独立数据框的箱线图?

在Base R中为折线图叠加箱线图的实现方法

核心思路

每个类别(cat)对应x轴上的固定位置,通过给不同x变量的箱线图设置微小偏移量避免重叠,再将箱线图直接叠加到已绘制的均值折线图上。

完整可运行代码

# 生成数据集(保留你的逻辑,修正随机数生成的参数写法)
cat <- rep(1:10, 10)
x1 <- rnorm(length(cat))
x2 <- rnorm(length(cat))
x3 <- rnorm(length(cat))
test_data <- data.frame(cat, x1, x2, x3)

# 计算各类别均值(你的原始代码)
plot_data <- data.frame(
  y = 1:10,
  x1_mean = tapply(test_data$x1, test_data$cat, mean),
  x2_mean = tapply(test_data$x2, test_data$cat, mean),
  x3_mean = tapply(test_data$x3, test_data$cat, mean)
)

# 绘制均值折线图,预留箱线图空间
plot(plot_data$y, plot_data$x1_mean, type = "b", 
     xlab = "类别", ylab = "数值", col = "blue", 
     ylim = c(-2, 2), xlim = c(0.7, 10.3),  # 扩大轴范围避免截断
     pch = 16)
lines(plot_data$y, plot_data$x2_mean, type = "b", col = "green", pch = 16)
lines(plot_data$y, plot_data$x3_mean, type = "b", col = "red", pch = 16)

# 定义箱线图偏移量、颜色和变量名
offsets <- c(-0.2, 0, 0.2)
colors <- c("blue", "green", "red")
x_vars <- c("x1", "x2", "x3")

# 循环叠加每个类别的箱线图
for (i in 1:10) {
  current_subset <- subset(test_data, cat == i)[, x_vars]
  boxplot(current_subset, at = i + offsets, add = TRUE, 
          border = colors, boxwex = 0.15, axes = FALSE)
}

# 添加图例关联折线与箱线图
legend("topright", legend = x_vars, col = colors, 
       pch = 16, lty = 1, bty = "n")

关键细节说明

  • 轴范围调整:xlim和ylim的设置是为了避免边缘的箱线图被画布截断,可根据你的实际数据分布灵活修改。
  • 偏移与宽度控制:offsets让同类别下的三个箱线图错开,boxwex缩小箱线图宽度,防止拥挤重叠。
  • 叠加逻辑:boxplot的add=TRUE参数是核心,实现将箱线图直接画在已有折线图上,axes=FALSE避免重复绘制坐标轴。
  • 复用性:如果你的子集数据结构和示例一致,只需替换test_data即可快速生成对应图表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 21:06:32