Tim
Tim

Reputation: 99556

Specify number of bins in hist() in R?

I try to specify number of bins in hist() in R to be 10, as follows

> hist(x, breaks=10)

But the number of bins is not exactly 10. I try several with other numbers of bins, and same thing happen.

?hist says breaks can specify

a single number giving the number of cells for the histogram.

So I wonder what I can do now? Thanks!

Upvotes: 3

Views: 8801

Answers (2)

Krzysztof Kulesza
Krzysztof Kulesza

Reputation: 11

Tim wrote in comments:

The problem with that is I specified brks = seq(min(x),max(x),length.out=500), but hist(x, breaks = brks) complained that some entries of x wouldn't be included in the histogram

I had the same problem. I suspect this happens because the value on the border of range is not counted. I have 2 solutions but non satisfies me in 100%.

Solution 1. When making the sequence, set minimum a little bit lower and maximum a little bit higher.

brks = seq(min(x)*.99999,max(x)*1.00001,length.out=500)

Solution 2. Instead of hist() use a combination of cut() and barplot(). The plot looks almost the same as hist, but doesn't produce a data frame like hist().

barplot(summary(cut(data, 10)), space=0)

Upvotes: 1

user3472874
user3472874

Reputation: 151

You can always create custom breakpoints

x   = rnorm(500)
brks = seq(-3,3,0.1)
hist(x, breaks = brks)

Upvotes: 2

Related Questions