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

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

enter image description here

Solution 2:

This is now a bit easier using the geomtextpath package:

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

Created on 2022-01-18 by the reprex package (v2.0.1)