Ben
Ben

Reputation: 21665

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

Upvotes: 4

Views: 6927

Answers (1)

mnel
mnel

Reputation: 115435

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!

Upvotes: 9

Related Questions