Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the position of bins in ggplot2 for R

The following plots a histogram with a bin whose left most point is at 0.

myplot = ggplot(df,aes(x = myvar)) +
         geom_histogram(aes(y = ..density..), binwidth = .3)  

I want the histogram to have a bin centered at 0. (In case you're wondering why I'd want to do such a wacky thing - it's to illustrate some weakness of histograms.)

like image 540
Ben Avatar asked Oct 22 '25 05:10

Ben


1 Answers

You can pass a breaks argument to stat_bin in the ..., (geom_histogram calls stat_bin)

myplot <-  ggplot(df,aes(x = myvar))+
 geom_histogram(aes(y = ..density..), breaks = seq(0,5,by=1))

This overrides bindwidth and origin

see the help for stat_bin for more details.

You may also find origin a useful parameter, (setting origin = 0 perhaps), but not in conjunction with breaks!

like image 137
mnel Avatar answered Oct 23 '25 18:10

mnel



Donate For Us

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