Box plot showing mean as a line

元气小坏坏 提交于 2019-12-22 05:04:44

问题


Is it possible to create a boxplot that shows both mean and median as a line with the standard boxplot function of R ? My current solution displays the mean as a cross:

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


回答1:


For the sake of completeness, you could also overplot:

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 that contains the lower whisker, the lower hinge, the median, the upper hinge and the extreme of the upper whisker for each boxplot. The solution above overwrites the median specified in bx.p$stats[3, ] with the mean value. The bxp function is a function to plot boxplot objects.

Result:




回答2:


The default plotting of boxplot makes the width of the box go from 0.8 to 1.2 in the x-axis.

You can hence draw a line for the mean with the below code:

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



来源:https://stackoverflow.com/questions/33689329/box-plot-showing-mean-as-a-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!