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

ggplot2, histogram, r

Solution

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`!

Problem

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.)

Original source