在密度图的顶部添加文本标签以标记不同的组 [英] Add text labels at the top of density plots to label the different groups

查看:90
本文介绍了在密度图的顶部添加文本标签以标记不同的组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下ggplot密度图

I have the following ggplot density plot

ggplot(mpg, aes(cty)) + geom_density(aes(fill=factor(cyl)))

如何删除图例,并在每个分布上方添加标签以表示其所属的组?

How do I remove the legend , and add labels above each distribution to denoted the group it belongs to?

推荐答案

就像策略.

Like it is said in the comment by @DavidKlotz, the maxima of the densities of cty per groups of cyl must be computed beforehand. I will do this with Hadley Wickham's split/lapply/combine strategy.

sp <- split(mpg$cty, mpg$cyl)
a <- lapply(seq_along(sp), function(i){
  d <- density(sp[[i]])
  k <- which.max(d$y)
  data.frame(cyl = names(sp)[i], xmax = d$x[k], ymax = d$y[k])
})
a <- do.call(rbind, a)

现在是情节.

ggplot(mpg, aes(cty)) + 
  geom_density(aes(fill = factor(cyl)), alpha = 0.5) +
  geom_text(data = a, 
            aes(x = xmax, y = ymax, 
                label = cyl, vjust = -0.5)) +
  scale_fill_discrete(guide = FALSE)

这篇关于在密度图的顶部添加文本标签以标记不同的组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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