在ggplot2 boxplot上添加多个标签

Alb*_*lba 5 r labels ggplot2

我试图在这个盒子图上添加两组男性和女性的平均年龄标签.到目前为止,我只能按组进行,而不是按性别和组进行.

我的数据框:

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)
Run Code Online (Sandbox Code Playgroud)

和剧情的命令:

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)
Run Code Online (Sandbox Code Playgroud)

图表包含2组和每组2个性别

ili*_*lir 10

为了清楚起见,您应该将聚合数据保存在单独的对象上,并position=position_dodge()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))
Run Code Online (Sandbox Code Playgroud)

与播放width,直到你满意的结果.请注意,我放入fill=Sex了全局aes定义,因此它也适用于文本标签.

编辑:在@ user20650上添加建议position_dodge()geom_boxplot()进行正确对齐.


use*_*650 7

如果您想要性别和群体的平均年龄,那么性别需要在汇总陈述中.

示例 - 这是你想要的吗?

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))
Run Code Online (Sandbox Code Playgroud)