3

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?

zx8754
  • 52,746
  • 12
  • 114
  • 209
Tony
  • 33
  • 3
  • Possible duplicate of [plot median values on top of a density distribution in ggplot2](https://stackoverflow.com/questions/33960277/plot-median-values-on-top-of-a-density-distribution-in-ggplot2) – David Klotz Aug 06 '19 at 18:18
  • Removing the legend is easy: `ggplot()... + scale_fill_discrete(guide = F)`. To add labels you'll need to calculate the x and y positions in advance – David Klotz Aug 06 '19 at 18:20
  • 1
    Not a dupe of that linked question, since that doesn't put the text at the peak of the density. – Axeman Aug 06 '19 at 19:49

2 Answers2

4

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

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
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)

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87