Search code examples
rplotggplot2histogram

R - ggplot2 - Right interval option in geom_histogram


Having this data that ranges from 0.42 to 1:

> summary(performance$SPC8)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
 0.4210  0.7805  0.8590  0.8359  0.9220  1.0000    

I did the following histogram:

ggplot(performance, aes(x=SPC8)) + 
  geom_histogram(aes(y = 100*(..count.. /74)), binwidth=.1, colour="black", fill="cadetblue3") + 
  geom_vline(aes(xintercept=mean(SPC8, na.rm=T)),color="red", linetype="dashed", size=1) +
  format_options

enter image description here How can I change the code above so that no bin is after "1"?


Solution

  • geom_histogram() uses stat_bin() to divide your data in bins. Default value for stat_bin() is right=FALSE that means that class start with value including and end with value not including this value, for example, class 0.9-1 will include 0.9 but won't include 1. To change this to oposite direction just add right=TRUE to geom_histogram().

     ggplot(performance, aes(x=SPC8)) + 
      geom_histogram(aes(y = 100*(..count.. /74)), binwidth=.1, colour="black",
             fill="cadetblue3",right=TRUE) + 
      geom_vline(aes(xintercept=mean(SPC8, na.rm=T)),color="red", linetype="dashed", size=1)