【问题标题】:Add multiple labels on ggplot2 boxplot在 ggplot2 boxplot 上添加多个标签
【发布时间】:2014-04-27 20:28:16
【问题描述】:

我正在尝试在此箱线图上为 2 组添加带有男性和女性平均年龄的标签。到目前为止,我只能按组进行,但不能按性别和组进行。

我的数据框:

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)

【问题讨论】:

  • 能否提供一些最小的数据,以便我们直接测试代码?
  • @ilir 我在帖子的编辑版本上添加了一些数据
  • @Alba this 可能会有所帮助。

标签: r ggplot2 labels


【解决方案1】:

为清楚起见,您可能应该将聚合数据保存在单独的对象中,并在 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() 以进行正确对齐。

【讨论】:

    【解决方案2】:

    如果您想要性别和组的平均年龄,那么性别需要在汇总语句中。

    示例 - 这是您想要的吗?

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

    【讨论】:

    • @Alba;您可以在geom_text 调用中使用vjust 参数来调整文本的y 位置,即。添加vjust = 1
    • 谢谢你,上面的 Ilir,你给了我想要的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 2018-08-01
    • 1970-01-01
    • 2014-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多