在密度图的顶部添加文本标签以标记不同的组

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

我有以下 ggplot 密度图

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

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

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

现在使用 geomtextpath 包更容易一些:

library(geomtextpath)
#> Loading required package: ggplot2

ggplot(mpg, aes(cty, fill=factor(cyl))) + 
  geom_density(alpha = 0.5) + 
  geom_textdensity(aes(label = cyl), 
                   hjust = "ymax", 
                   vjust = -0.5, text_only = TRUE, text_smoothing = 20) + 
  ylim(c(0, 0.6)) +
  theme(legend.position = "none")

reprex package (v2.0.1)

创建于 2022-01-18