I am trying to add labels with the mean age of the males and females on this boxplot for 2 groups. So far I was only able to do it by group but not by gender and group.
My data frame:
Age=c(60, 62, 22, 24, 21, 23)
Sex=c("f", "m", "f","f","f","m")
Group=c("Old", "Old", "Young", "Young", "Young", "Young")
aging<-data.frame(Age, Sex, Group)
And the command for the plot:
ggplot(data=aging, aes(x=Group, y=Age))+geom_boxplot(aes(fill=Sex))
+geom_text(data =aggregate(Age~Group,aging, mean),
aes(label =round(Age,1), y = Age + 3), size=6)
If you are wanting the mean age for gender and group then gender need to be in the aggregate statement.
Example - is this what you want?
You should probably save the aggregate data on a separate object for clarity and use
position=position_dodge()
in thegeom_text()
options:Play with the
width
till you are satisfied with the results. Notice that I putfill=Sex
in the globalaes
definition so it applies to the text labels as well.Edit: On @user20650 suggestion added
position_dodge()
togeom_boxplot()
for proper alignment.