Add text labels at the top of density plots to label the different groups

ぃ、小莉子 提交于 2020-05-09 05:41:51

问题


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?


回答1:


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)

Now the plot.

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)



来源:https://stackoverflow.com/questions/57381627/add-text-labels-at-the-top-of-density-plots-to-label-the-different-groups

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!