在 Base R 绘图的单个箱线图中添加水平 "separating" 线

adding horizontal "separating" lines in a single boxplot in Base R plotting

我需要在 Base R 箱线图中添加一条“分隔线”来分隔不同的组。在下面的示例中,我想使用水平线(红色)分隔 A 组和 B 组(每个组有 2 个级别)。可重现结果的 R 代码:

dat = data.frame(A1 = rnorm(1000, 0, 1), A2 = rnorm(1000, 1, 2),
                 B1 = rnorm(1000, 0.5, 0.5), B2 = rnorm(1000, 1.5, 1.5))
boxplot(dat, horizontal = T, outline=F)

在 Base R 中有简单的方法吗?

另外,有没有简单的方法给 y 轴标签上色?我想让 A1 和 B1 在轴上显示为红色,A2 和 B2 显示为蓝色。

谢谢!

使用abline。要获得正确的位置,请取 y-axis.

axTicks 的平均值

要获得彩色标签,首先省略 yaxt 并重建 axis 个刻度和 mtext,同样使用 axTicks

b <- boxplot(dat, horizontal=T, outline=F, yaxt="n")
ats <- axTicks(2)
axis(2, labels=F)
mtext(b$names, 2, 1, col=c(2, 4), at=ats)
abline(h=mean(ats), lwd=2, col=2)

如果您想要与标签相对应的轴刻度标签颜色,请改用segments

b <- boxplot(dat, horizontal=T, outline=F, yaxt="n")
ats <- axTicks(2)
abline(h=mean(ats), lwd=2, col=2)
pu <- par()$usr
Map(function(x, y) segments(pu[1] - .2, x, pu[1], x, xpd=T, col=y), ats, c(2, 4))
mtext(b$names, 2, 1, col=c(2, 4), at=ats)

编辑: 要稍微调整 space 使用 boxplot 中的 at= 选项并省略中间的 axTicks.

b <- boxplot(dat, horizontal=T, outline=F, yaxt="n", at=c(1, 2, 4, 5))
ats <- axTicks(2)[-3]
abline(h=mean(ats), lwd=2, col=2)
pu <- par()$usr
Map(function(x, y) segments(pu[1] - .2, x, pu[1], x, xpd=T, col=y), ats, c(2, 4))
mtext(b$names, 2, 1, col=c(2, 4), at=ats)