Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 722
Sam Avatar asked Jan 07 '13 16:01

Sam


People also ask

How do I change my Binwidth?

To adjust the bin width, right click the horizontal axis on the histogram and then click Format Axis from the dropdown: What is this? In the window that appears to the right, we can see that Excel chose the bin width to be 29,000. We can change this to any number we'd like.

How do I change the bin size in Ggplot?

To change the number of bins in the histogram using the ggplot2 package library in the R Language, we use the bins argument of the geom_histogram() function. The bins argument of the geom_histogram() function to manually set the number of bars, cells, or bins the whole histogram will be divided into.

What does Binwidth mean in R?

binwidth. The width of the bins. Can be specified as a numeric value, or a function that calculates width from x. The default is to use bins bins that cover the range of the data. You should always override this value, exploring multiple widths to find the best to illustrate the stories in your data.


1 Answers

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")
like image 91
Roland Avatar answered Sep 28 '22 11:09

Roland