Muhammad Kamil
Muhammad Kamil

Reputation: 665

Getting bin width of a histogram in R

I've made a histogram as follows:

data(mtcars)
hist(mtcars$disp)

How do I find out the bin width in the above histogram?

Regards

Upvotes: 1

Views: 1853

Answers (2)

user2554330
user2554330

Reputation: 44877

Save the result of the hist() call, then extract the breaks:

h <- hist(mtcars$disp)

h$breaks
#>  [1]  50 100 150 200 250 300 350 400 450 500
# To get the widths, use diff().  Here all are the same:
unique(diff(h$breaks))
#> [1] 50

Created on 2021-09-06 by the reprex package (v2.0.0)

Thanks to @BenBolker for the suggestion to calculate the width explicitly.

Upvotes: 2

TarJae
TarJae

Reputation: 78927

R does a number of things by default in creating a histogram

You can print out this parameters of the histogram by assigning to an an objec histinfo and then printing:

breaks will give you the bin width:

histinfo<-hist(mtcars$disp)
histinfo

> histinfo
$breaks
 [1]  50 100 150 200 250 300 350 400 450 500

$counts
[1] 5 7 4 1 4 4 4 1 2

$density
[1] 0.003125 0.004375 0.002500 0.000625 0.002500 0.002500 0.002500
[8] 0.000625 0.001250

$mids
[1]  75 125 175 225 275 325 375 425 475

$xname
[1] "mtcars$disp"

$equidist
[1] TRUE

attr(,"class")
[1] "histogram"

Upvotes: 3

Related Questions