在箱线图中添加多条水平线

Add multiple horizontal lines in a boxplot

我知道我可以使用像

这样的命令向箱线图添加水平线
abline(h=3)

当一个面板中有多个箱线图时,我可以为每个箱线图添加不同的水平线吗?

在上图中,我想为 1 添加行 'y=1.2',为 2 添加行 'y=1.5',为 3 添加行 'y=2.1'。

我不确定我是否完全理解你想要的,但可能是这样的:为每个箱线图添加一条线,覆盖与箱线图相同的 x 轴范围。

框的宽度由 pars$boxwex 控制,默认设置为 0.8。从boxplot.default:

的参数列表可以看出
formals(boxplot.default)$pars
## list(boxwex = 0.8, staplewex = 0.5, outwex = 0.5)

因此,以下为每个箱线图生成一条线段:

# create sample data and box plot
set.seed(123)
datatest <- data.frame(a = rnorm(100, mean = 10, sd = 4),
                       b = rnorm(100, mean = 15, sd = 6),
                       c = rnorm(100, mean = 8, sd = 5))
boxplot(datatest)

# create data for segments
n <- ncol(datatest)
# width of each boxplot is 0.8
x0s <- 1:n - 0.4
x1s <- 1:n + 0.4
# these are the y-coordinates for the horizontal lines
# that you need to set to the desired values.
y0s <- c(11.3, 16.5, 10.7)

# add segments
segments(x0 = x0s, x1 = x1s, y0 = y0s, col = "red")

这给出了以下情节: