2014-04-27 137 views
4

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

我的数据帧:

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

+0

你能提供一些最小的数据,所以我们可以直接测试代码吗? – ilir

+0

@ilir我在编辑后的版本 – Alba

+0

@Alba [this](http://stackoverflow.com/a/13370258/640783)上添加了一些数据可能会有所帮助。 –

回答

8

你或许应该保存为清楚起见单独对象上的汇总数据,并在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,直到你满意的结果。请注意,我将fill=Sex放在全局aes定义中,因此它也适用于文本标签。

编辑:在@ user20650建议添加position_dodge()geom_boxplot()为正确对齐。

+0

是的,非常感谢您的帮助,我正在寻找 – Alba

+0

@ user20650谢谢,添加到答案。 – ilir

+0

@ilir;好东西 – user20650

6

如果你想要的平均年龄性别和组接性别需在汇总报表中。

示例 - 这是你想要的吗?

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

+0

谢谢你,Ilir上面,你给我我正在寻找的答案 – Alba