Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get values and positions to label a ggplot histogram

Tags:

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?

like image 859
Shoaibkhanz Avatar asked Jun 13 '14 06:06

Shoaibkhanz


2 Answers

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

labeled univariate ggplot2 barplot

like image 124
MrFlick Avatar answered Sep 19 '22 17:09

MrFlick


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

enter image description here

like image 27
Arun Kumar Khattri Avatar answered Sep 20 '22 17:09

Arun Kumar Khattri