Below code works well and it labels the barplot correctly, However, if I try geom_text for a histogram I fail since geom_text requires a y-component and a histogram's y component is not part of the original data.
Label an "ordinary" bar plot (geom_bar(stat = "identity") works well:
ggplot(csub, aes(x = Year, y = Anomaly10y, fill = pos)) + geom_bar(stat = "identity", position = "identity") + geom_text(aes(label = Anomaly10y,vjust=1.5)) My Problem: How to get the correct y and label (indicated by ?) for geom_text, to put labels on top of the histogram bars
ggplot(csub,aes(x = Anomaly10y)) + geom_histogram() geom_text(aes(label = ?, vjust = 1.5)) geom_text requires x, y and labels. However, y and labels are not in the original data, but generated by the geom_histogram function. How can I extract the necessary data to position labels on a histogram?
geom_histogram() is just a fancy wrapper to stat_bin so you can all that yourself with the bars and text that you like. Here's an example
#sample data set.seed(15) csub<-data.frame(Anomaly10y = rpois(50,5)) And then we plot it with
ggplot(csub,aes(x=Anomaly10y)) + stat_bin(binwidth=1) + ylim(c(0, 12)) + stat_bin(binwidth=1, geom="text", aes(label=..count..), vjust=-1.5) to get

Ok to make it aesthetically appealing here is the solution:
set.seed(15) csub <- data.frame(Anomaly10y = rpois(50, 5)) Now Plot it
csub %>% ggplot(aes(Anomaly10y)) + geom_histogram(binwidth=1) + stat_bin(binwidth=1, geom='text', color='white', aes(label=..count..), position=position_stack(vjust = 0.5)) resultant plot will be

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With