Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add multiple horizontal lines in a boxplot

Tags:

r

line

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?

enter image description here

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.

like image 866
user67275 Avatar asked Dec 19 '15 01:12

user67275


1 Answers

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:

enter image description here

like image 188
Stibu Avatar answered Sep 24 '22 01:09

Stibu