Drawing lines across base R boxplots

I would like to draw some lines across the boxplots produced by base R (specifically, a line at group means, then bounds at ±sqrt(2)*CI). I've found a way to draw dots at the group means, to wit:

mymtcars <- mtcars
mymtcars$am <- as.factor(mymtcars$am)
boxplot(mpg ~ am, data=mymtcars, boxwex = 0.15)
means <- tapply(mymtcars$mpg, mymtcars$am, mean)
points(means,col = "red",pch = 18)

...but I'm getting stymied by finding the width of the boxes. The documentation is about three layers deep, and I've tried many combinations of the bxt pars, to no avail.

If it helps, you can see the docs for boxplot which leads to bxp, which has options for both pars() (listed on the aforementioned bxp page) and par(). Some of these set values, some retrieve values, some do both, but I'm having a bit of trouble figuring out which is which.

This seems to work:

mymtcars <- mtcars
mymtcars$am <- as.factor(mymtcars$am)
bw = 0.15
boxplot(mpg ~ am, data=mymtcars, boxwex = bw)
means <- tapply(mymtcars$mpg, mymtcars$am, mean)
points(means,col = "red",pch = 18)

segments(x0 = c(1,2) - bw/2, 
         y0 = means, 
         x1 = c(1,2) + bw/2, 
         y1 = means, 
         col = "red", lwd = 3)

Created on 2019-03-24 by the reprex package (v0.2.1)

By default the boxes are drawn at 1:n where n is the number of groups. By setting the boxwex parameter in the call to boxplot() you override the scaling which boxplot() normally does, so you can know the widths of the boxes.

Actually, the default scaling of the box width is just boxwex = 0.8, so you can just do the following.

mymtcars <- mtcars
mymtcars$am <- as.factor(mymtcars$am)

boxplot(mpg ~ am, data=mymtcars)
means <- tapply(mymtcars$mpg, mymtcars$am, mean)
points(means,col = "red",pch = 18)
bw = 0.8
segments(x0 = c(1,2) - bw/2, 
         y0 = means, 
         x1 = c(1,2) + bw/2, 
         y1 = means, 
         col = "red", lwd = 3)

Created on 2019-03-24 by the reprex package (v0.2.1)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.