在ggplot2的箱线图上添加多个标签

9
我将尝试为这两组的箱线图添加男性和女性平均年龄标签。到目前为止,我只能按组别而不是按性别和组别来做到这一点。
我的数据框如下:
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)

绘图命令:

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


你能提供一些最小的数据,以便我们可以直接测试代码吗? - ilir
@ilir 我在编辑后的帖子中添加了一些数据。 - Alba
@Alba 这个链接可能会有所帮助:https://dev59.com/BmYr5IYBdhLWcg3w0taE#13370258。 - Paulo E. Cardoso
2个回答

12

为了更清晰地保存聚合数据并在geom_text()选项中使用position=position_dodge()

Translated text:

为了更清晰地保存聚合数据,您应该将其存储在单独的对象上,并在geom_text()选项中使用position=position_dodge()

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

调整width直到你对结果满意。请注意,我在全局的aes定义中添加了fill=Sex,这样它也适用于文本标签。

编辑:根据@user20650的建议,将position_dodge()添加到geom_boxplot()以进行正确对齐。


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


1
@Alba;你可以在geom_text调用中使用vjust参数来微调文本的y位置,例如添加vjust = 1 - user20650
谢谢你,Ilir以及你给了我我所寻找的答案。 - Alba

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接