Graph showing average as a line

Is it possible to create a rectangle that shows both the middle and the median, as a line with the standard boxplot function from R? My current solution displays the average as a cross:

set.seed(1234) values <- runif(10,0,1) boxplot(values) points(mean(values),col="red",pch=4,lwd = 4) 

Image of boxplot

+7
r mean boxplot
source share
2 answers

For completeness, you can also overpay:

 set.seed(753) df <- data.frame(y=rt(100, 4), x=gl(5, 20)) bx.p <- boxplot(y~x, df) bx.p$stats[3, ] <- unclass(with(df, by(y, x, FUN = mean))) bxp(bx.p, add=T, boxfill="transparent", medcol="red", axes=F, outpch = NA, outlty="blank", boxlty="blank", whisklty="blank", staplelty="blank") 

Explanation via @scs:

bxp$stats returns a matrix containing the lower whisker, lower hinge, median, upper loop and extreme upper thread for each box. The solution above overwrites the median specified in bx.p$stats[3, ] with an average value. The bxp function is a function for constructing boxplot objects.

Result:

enter image description here

+9
source share

The default boxplot makes the field width 0.8 to 1.2 in x-axis .

Thus, you can draw a line for the average using the code below:

 lines(c(0.8, 1.2), rep(mean(values), 2), col="red", lwd = 2) 

enter image description here

+9
source share

All Articles