In diesem Boxplot können wir den Mittelwert sehen, aber wie können wir auch den Zahlenwert für jeden Mittelwert jedes Boxplots auf dem Diagramm haben?
ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot() +
stat_summary(fun.y=mean, colour="darkred", geom="point",
shape=18, size=3,show_guide = FALSE)
Zunächst können Sie die Gruppenmittelwerte mit aggregate
berechnen:
means <- aggregate(weight ~ group, PlantGrowth, mean)
Dieser Datensatz kann mit geom_text
verwendet werden:
library(ggplot2)
ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot() +
stat_summary(fun.y=mean, colour="darkred", geom="point",
shape=18, size=3,show_guide = FALSE) +
geom_text(data = means, aes(label = weight, y = weight + 0.08))
Hier wird + 0.08
verwendet, um das Etikett über dem Punkt zu platzieren, der den Mittelwert darstellt.
Eine alternative Version ohne 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)
Sie können den Ausgabewert von stat_summary()
verwenden.
ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group))
+ geom_boxplot()
+ stat_summary(fun.y=mean, colour="darkred", geom="point", hape=18, size=3,show_guide = FALSE)
+ stat_summary(fun.y=mean, colour="red", geom="text", show_guide = FALSE,
vjust=-0.7, aes( label=round(..y.., digits=1)))
Sie können auch eine Funktion in stat_summary verwenden, um den Mittelwert und das Argument hjust zum Platzieren des Textes zu berechnen. Sie benötigen eine zusätzliche Funktion, aber keinen zusätzlichen Datenrahmen:
fun_mean <- function(x){
return(data.frame(y=mean(x),label=mean(x,na.rm=T)))}
ggplot(PlantGrowth,aes(x=group,y=weight)) +
geom_boxplot(aes(fill=group)) +
stat_summary(fun.y = mean, geom="point",colour="darkred", size=3) +
stat_summary(fun.data = fun_mean, geom="text", vjust=-0.7)
Ich weiß, dass es bereits eine akzeptierte Antwort gibt, aber ich wollte mit Hilfe von magrittr package einen coolen Weg zeigen, um dies in einem einzigen Befehl auszuführen.
PlantGrowth %$% # open dataset and make colnames accessible with '$'
split(weight,group) %T>% # split by group and side-pipe it into boxplot
boxplot %>% # plot
lapply(mean) %>% # data from split can still be used thanks to side-pipe '%T>%'
unlist %T>% # convert to atomic and side-pipe it to points
points(pch=18) %>% # add points for means to the boxplot
text(x=.+0.06,labels=.) # use the values to print text
Dieser Code erzeugt ein Boxplot, dessen Mittel als Punkte und Werte gedruckt werden:
Ich teile den Befehl in mehrere Zeilen auf, damit ich kommentieren kann, was jeder Teil tut. Er kann aber auch als Oneliner eingegeben werden. Mehr dazu erfahren Sie in meinem Gist .