在ggplot2 boxplot上添加多个标签 [英] Add multiple labels on ggplot2 boxplot

查看:309
本文介绍了在ggplot2 boxplot上添加多个标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在这个boxplot上添加两组男性和女性平均年龄的标签。到目前为止,我只能通过小组来完成,而不是通过性别和小组来完成。



我的数据框:

 年龄= c(60,62 ,22,24,21,23)
性别= c(f,m,f,f,f,m)
Group = c(老年,年老,年轻,年轻)

老化<-data.frame(年龄,性别,群体)

以及该命令的情节:

  ggplot(data = aging,aes(x = Group,y = Age))+ geom_boxplot(aes(fill = Sex))
+ geom_text(data = aggregate(Age〜Group,ageing,mean) ,
aes(label = round(Age,1),y = Age + 3),size = 6)


<为了清晰起见,您应该将汇总数据保存在单独的对象上,并使用 position = position_dodge() geom_text()选项:

  aging.sum = aggregate(Age 〜组+性别,年龄,平均值)

ggplot(数据=年龄,aes(x =组,y =年龄,填充= Se x))+
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))

code> width ,直到您对结果满意为止。请注意,我在全局 aes 定义中放置了 fill = Sex ,所以它也适用于文本标签。



编辑:在@ user20650建议中添加了 position_dodge() geom_boxplot()以便正确对齐。


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)

解决方案

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.

这篇关于在ggplot2 boxplot上添加多个标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆