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

如何在R中将两个矩阵的行向箱线图并排绘制于同一图形?

嘿,我来帮你搞定这个箱线图合并的问题!你用par(new=TRUE)出现重叠是因为这个参数只是在同一张画布上叠加新图层,根本没调整X轴的位置,两个图的X坐标完全重合,自然就叠在一起啦。下面给你两种实用的解决方案:

方法一:使用R基础绘图系统

我们可以手动调整第二个箱线图的X轴位置,让A和B对应行的箱线图并排显示:

# 生成示例数据
A <- matrix( rnorm(100), ncol = 5 )
B <- matrix( rnorm(100), ncol = 5 )

# 转置矩阵,让每行变成一列(boxplot默认按列生成箱线图,刚好对应原矩阵的行)
A_by_row <- as.data.frame(t(A))
B_by_row <- as.data.frame(t(B))

# 先绘制A的箱线图,设置X轴范围预留出B的位置
boxplot(A_by_row, 
        col = "red", 
        xlim = c(0.5, 20.9),  # 扩展X轴范围,容纳B的偏移位置
        names = 1:20,        # X轴标签设为行号
        main = "Row-wise Boxplots of A & B",
        ylab = "Value")

# 添加B的箱线图,用`at`参数偏移X轴位置,实现并排
boxplot(B_by_row, 
        col = "green", 
        at = 1:20 + 0.4,  # 每个箱线图向右偏移0.4
        add = TRUE)        # 叠加到已有图形上

# 添加图例区分A和B
legend("topright", 
       legend = c("Matrix A", "Matrix B"), 
       fill = c("red", "green"))
方法二:使用ggplot2(推荐)

ggplot2对长格式数据的支持更好,代码更直观,也更容易调整样式:

library(ggplot2)

# 生成示例数据
A <- matrix( rnorm(100), ncol = 5 )
B <- matrix( rnorm(100), ncol = 5 )

# 将矩阵转换为长格式数据框
# 处理矩阵A
A_long <- data.frame(
  value = as.vector(A),
  row_num = rep(1:nrow(A), each = ncol(A)),  # 标记每个值所属的行
  source = rep("Matrix A", length(A))        # 标记来源是A
)

# 处理矩阵B
B_long <- data.frame(
  value = as.vector(B),
  row_num = rep(1:nrow(B), each = ncol(B)),
  source = rep("Matrix B", length(B))
)

# 合并两个数据框
combined_data <- rbind(A_long, B_long)

# 绘制并排箱线图
ggplot(combined_data, aes(x = factor(row_num), y = value, fill = source)) +
  geom_boxplot(position = position_dodge(width = 0.8)) +  # 自动错开箱线图位置
  scale_fill_manual(values = c("Matrix A" = "red", "Matrix B" = "green")) +
  labs(x = "Row Number", y = "Value", title = "Row-wise Boxplots of Matrix A and B") +
  theme_bw()  # 套用简洁的主题

这两种方法都能实现A和B的行向箱线图并排显示、共享X轴的效果,其中ggplot2的方式更易维护和扩展样式~

内容的提问来源于stack exchange,提问作者D.Derek

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:22:59