wthimdh
wthimdh

Reputation: 486

How to put the legends in the peaks of multiple distributions using ggplot?

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!

Upvotes: 3

Views: 333

Answers (1)

g_t_m
g_t_m

Reputation: 714

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

Upvotes: 3

Related Questions