First, you can calculate the group means with aggregate
:
means <- aggregate(weight ~ group, PlantGrowth, mean)
This dataset can be used with geom_text
:
library(ggplot2)
ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot() +
stat_summary(fun=mean, colour="darkred", geom="point",
shape=18, size=3, show.legend=FALSE) +
geom_text(data = means, aes(label = weight, y = weight + 0.08))
Here, + 0.08
is used to place the label above the point representing the mean.
An alternative version without ggplot2
:
means <- aggregate(weight ~ group, PlantGrowth, mean)
boxplot(weight ~ group, PlantGrowth)
points(1:3, means$weight, col = "red")
text(1:3, means$weight + 0.08, labels = means$weight)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…