Sam
Sam

Reputation: 8202

How to adjust `binwidth` in ggplot2?

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.

Upvotes: 17

Views: 47321

Answers (1)

Roland
Roland

Reputation: 132969

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

Upvotes: 18

Related Questions