你可以用以下方法在R语言中画一个带有平均值的boxplot。
方法1:使用Base R
#create boxplots
boxplot(df$values~df$group)
#calculate mean value by group
means <- tapply(df$values, df$group, mean)
#add means as circles to each boxplot
points(means, pch=20)
方法2:使用ggplot2
library(ggplot2)
#create boxplots with mean values shown as circles
ggplot(df, aes(x=group, y=values, fill=group)) +
geom_boxplot() +
stat_summary(fun=mean, geom='point', shape=20)
下面的例子展示了如何在R语言中用以下数据框架实际使用每种方法:
#create data frame
df <- data.frame(team=rep(c('A', 'B', 'C'), each=5),
points=c(4, 4, 5, 6, 8, 7, 6, 8, 9, 12,
11, 12, 13, 16, 18))
#view first six rows of data frame
head(df)
team points
1 A 4
2 A 4
3 A 5
4 A 6
5 A 8
6 B 7
例子1:在Base R中创建带有均值的Boxplots
下面的代码展示了如何在基础R中创建带有均值的boxplots:
#create boxplots
boxplot(df$points~df$team)
#calculate mean value by group
means <- tapply(df$points, df$team, mean)
#add means as circles to each boxplot
points(means, pch=20, cex=1.5)

每个boxplot里面的黑线代表中位数,每个boxplot里面的黑圈代表平均值。
注意:改变cex参数的值来改变圆的大小。
例2:在ggplot2中创建带有平均值的博列表
下面的代码显示了如何在ggplot2中创建带有平均值的boxplots:
library(ggplot2)
#create boxplots with mean values
ggplot(df, aes(x=team, y=points, fill=team)) +
geom_boxplot() +
stat_summary(fun=mean, geom='point', shape=20, size=8) +
theme(legend.position='none')

每个boxplot里面的黑线代表中位数,每个boxplot里面的黑圈代表平均值。
注意:改变stat_summary()函数中size 参数的值来改变圆的大小。
其他资源
下面的教程提供了关于箱形图的额外信息: