Add multiple tags to ggplot2 boxplot

I am trying to add labels with the average age of men and women in this box for 2 groups. Until now, I could only do this 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

+4
source share
2 answers

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

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 widthuntil you are satisfied with the results. Note that I put fill=Sexin the global definition aes, so it also applies to text labels.

: @user20650 position_dodge() geom_boxplot() .

+9

, .

- , ?

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))

+6

Source: https://habr.com/ru/post/1538313/


All Articles