How to adjust `binwidth` in ggplot2?

Sam picture Sam · Jan 7, 2013 · Viewed 35.4k times · Source

This may sound a like a repeat question, but hopefully it is not. In the basic R graphics histogram function, we have a option breaks="FD", which gives a reasonable sized binsize for the histogram, do we have any similar simple option for ggplot2? Or even better can we use the same option in ggplot2?

I do understand that you can adjust the binwidth in geom_histogram, but i am looking for a more simpler way to generate aesthetically pleasing and resonable binsize.

Answer

Roland picture Roland · Jan 7, 2013
set.seed(42)
x <- rnorm(1000)
hist(x,breaks="FD")

library(ggplot2)
breaks <- pretty(range(x), n = nclass.FD(x), min.n = 1)
bwidth <- breaks[2]-breaks[1]
df <- data.frame(x)
ggplot(df,aes(x))+geom_histogram(binwidth=bwidth,fill="white",colour="black")