peuhp
peuhp

Reputation:

geom_text and grouping

Here is a piece of ggplot2 code plotting a set of 4 densities from samples:

library('reshape')
library('ggplot2')
data <- matrix(0,5,100)
for(i in seq(1,5,1)){
  data[i,] <- rnorm(100,i,1)
}
df <- data.frame(melt(data))
g <- ggplot(data=df, aes(x=value,group=X1)) + 
  geom_density(fill="blue",alpha=0.5)
g

I would like to add the "index" of the density at the top of each of them. I tried many things including:

g + geom_text(aes(label=X1,y=0.5,group=X1));

Which does not give me what I expect but the index of the densities for each sample (as it was ignoring the "group" argument). I am surely missing something but what?

Upvotes: 0

Views: 4035

Answers (1)

Sven Hohenstein
Sven Hohenstein

Reputation: 81753

The problem is: ggplot prints the label for each data point. You first need to calculate the center of the distributions:

df2 <- aggregate(value ~ X1, df, function(x) mean(range(x))/2)

This returns the center for each X1 group. Then, the new data frame, df2 can be used with the geom_text function:

ggplot(data = df,aes(x = value, group = X1))+
  geom_density(fill = "blue", alpha = 0.5) +
  geom_text(data = df2, aes(label = X1, y = 0.5))

enter image description here

Alternatively, you could calculate the positions of the densities' peaks:

df2 <- aggregate(value ~ X1, df, function(x) {
  dens <- density(x)
  return(dens$x[which.max(dens$y)])
})

enter image description here

Upvotes: 6

Related Questions