3

I want to place the legend of each histogram over its peak instead of the right of the figure in R. Let me explain it with a pseudo data set:

a <- rnorm(100, mean = 20, sd = 1)
b <- rnorm(100, mean = 22, sd = 1)
aleg <- rep("A",length(a))
bleg <- rep("B",length(b))
data <- data.frame(value=c(a,b), variable=c(lega,legb))
ggplot(data,aes(x=value, fill=variable)) + geom_density(alpha=0.25) + labs(fill="")

which gives you:

enter image description here

This is what I want:

enter image description here

I have a big data set that has ~8 different variables. That's why I want a quick solution instead of adding individual text boxes.

Thanks in advance!

wthimdh
  • 476
  • 1
  • 5
  • 19
  • 1
    Maybe grab the values of the curves or pre-calculate them ([What algorithm does geom_density() use and how to extract points/equation of curves?](https://stackoverflow.com/questions/12394321/r-what-algorithm-does-geom-density-use-and-how-to-extract-points-equation-of)) and use them in a `geom_text`? – Henrik Jan 10 '19 at 19:56
  • 1
    Possible duplicate: [ggplot2: how to add sample numbers to density plot?](https://stackoverflow.com/questions/43207655/ggplot2-how-to-add-sample-numbers-to-density-plot) – Henrik Jan 10 '19 at 20:03
  • 1
    Haven't tried, but maybe worth checking: [`ggpmisc::stat_peak`](https://cran.r-project.org/web/packages/ggpmisc/vignettes/user-guide.html#stat_peaks-and-stat_valleys) – Henrik Jan 10 '19 at 20:05

1 Answers1

3

How's this?

library(ggplot2)

set.seed(1)
a <- rnorm(100, mean = 20, sd = 1)
b <- rnorm(100, mean = 22, sd = 1)
aleg <- rep("A",length(a))
bleg <- rep("B",length(b))

data <- data.frame(value=c(a,b), variable=c(aleg,bleg))

labels <-
  lapply(split(data, data$variable), function(x){
    dens <- density(x$value)  # compute density of each variable

    data.frame(y = max(dens$y),  # get maximum density of each variable
               x = dens$x[which(dens$y == max(dens$y))],  # get corresponding x value
               label = x$variable[1])
  })

ggplot(data,aes(x=value, fill=variable)) + 
  geom_density(alpha=0.25) + 
  geom_text(data = do.call(rbind, labels), aes(x = x, y = y, label = label), 
            inherit.aes = F, 
            nudge_y = 0.03) +
  labs(fill="")

g_t_m
  • 704
  • 4
  • 9