简体   繁体   中英

Add multiple horizontal lines in a boxplot

I know that I can add a horizontal line to a boxplot using a command like

abline(h=3)

When there are multiple boxplots in a single panel, can I add different horizontal lines for each single boxplot?

在此输入图像描述

In the above plot, I would like to add lines 'y=1.2' for 1, 'y=1.5' for 2, and 'y=2.1' for 3.

I am not sure that I understand exactly, what you want, but it might be this: add a line for each boxplot that covers the same x-axis range as the boxplot.

The width of the boxes is controlled by pars$boxwex which is set to 0.8 by default. This can be seen from the argument list of boxplot.default :

formals(boxplot.default)$pars
## list(boxwex = 0.8, staplewex = 0.5, outwex = 0.5)

So, the following produces a line segment for each boxplot:

# 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")

This gives the following plot:

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM