You can label the bars using stat_bin
with geom="text"
. stat_bin
calculates 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")
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")