Search code examples
rggplot2geom-text

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


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?


Solution

  • 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