Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

density histogram in ggplot2: label bar height [duplicate]

I have data that tells me how many minutes were required to solve a task:

dat = data.frame(a = c(5.5,7,4,20,4.75,6,5,8.5,10,10.5,13.5,14,11))

I plotted a density histogram of the data with the ggplot2 package:

p=ggplot(dat, aes(x=a)) + geom_histogram(aes(y=..density..),breaks = seq(4,20,by=2))+xlab("Required Solving Time")

Now I would like to add labels of the height of every density bar on top of it. I tried to reach this by adding +geom_text(label=..density..). This returns the error

object '..density..' not found

however. Does anyone know what the input of the geom_text() function has to be in my case to get those labels?

A solution without geom_text() is fine too but I would rather prefer to stay within the ggplot2 package.

like image 631
Alias Avatar asked Dec 24 '22 06:12

Alias


2 Answers

You can label the bars using stat_bin with geom="text". stat_bincalculates the counts, which we convert to densities using ..density.., just as for geom_histogram. But by setting geom="text", we display those density values as text. We also need to set the same breaks for geom_histogram and stat_bin so that the density values will match. I've placed the text labels in the middle of the bar by multiplying ..density.. by 0.5 in the label. However, you can of course adjust this however you please.

breaks = seq(4,20,by=2)  

ggplot(dat, aes(x=a)) + 
  geom_histogram(aes(y=..density..), breaks = breaks) + 
  stat_bin(geom="text", aes(label=round(..density..,2), y=0.5*..density..), 
           breaks=breaks, colour="white") +
  xlab("Required Solving Time")

enter image description here

To get the labels just above the bars, you can use:

ggplot(dat, aes(x=a)) + 
  geom_histogram(aes(y=..density..), breaks = breaks) + 
  stat_bin(geom="text", aes(label=round(..density..,2), y=..density..),
           breaks=breaks, vjust = -1) +
  xlab("Required Solving Time")

enter image description here

like image 88
eipi10 Avatar answered Dec 28 '22 08:12

eipi10


..density.. comes from the stat, so you need to tell this layer to also use a binning statistic,

p + geom_text(aes(label=round(..density.., 2), y=..density..), 
              stat="bin", breaks = seq(4,20,by=2), 
              col="white", vjust=1)

enter image description here

like image 23
baptiste Avatar answered Dec 28 '22 06:12

baptiste