9

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)

Graph with 2 groups and 2 genders per group

3
  • Could you provide some minimal data so we can test the code directly? Commented Apr 27, 2014 at 20:34
  • @ilir I added some data on the edited version of the post Commented Apr 27, 2014 at 20:47
  • @Alba this may help. Commented Apr 27, 2014 at 20:49

2 Answers 2

12

You should probably save the aggregate data on a separate object for clarity and use position=position_dodge() in the geom_text() options:

aging.sum = aggregate(Age ~ Group + Sex, aging, mean)

ggplot(data=aging, aes(x=Group, y=Age, fill=Sex)) + 
  geom_boxplot(position=position_dodge(width=0.8)) +
  geom_text(data=aging.sum, aes(label=round(Age,1), y = Age + 3), 
            size=6, position=position_dodge(width=0.8))

Play with the width till you are satisfied with the results. Notice that I put fill=Sex in the global aes definition so it applies to the text labels as well.

Edit: On @user20650 suggestion added position_dodge() to geom_boxplot() for proper alignment.

Sign up to request clarification or add additional context in comments.

Comments

7

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?

p <- ggplot(data=mtcars, aes(x=factor(vs), y=mpg, fill=factor(am))) +
                            geom_boxplot(position = position_dodge(width=0.9)) 

a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))

p +  geom_text(data = a, aes(label = mpg), 
                                  position = position_dodge(width=0.9))

2 Comments

@Alba; you can use the vjust argument in the geom_text call to tweak the y position of the text ie. add vjust = 1.
Thank you, Ilir above and you gave me the answer I was looking for

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.