【问题标题】:Getting bin width of a histogram in R在R中获取直方图的bin宽度
【发布时间】:2021-11-03 18:27:49
【问题描述】:

我做了一个直方图如下:

data(mtcars)
hist(mtcars$disp)

如何找出上述直方图中的 bin 宽度?

问候

【问题讨论】:

标签: r plot histogram


【解决方案1】:

保存hist() 调用的结果,然后提取中断:

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

reprex package (v2.0.0) 于 2021 年 9 月 6 日创建

感谢@BenBolker 提出明确计算宽度的建议。

【讨论】:

    【解决方案2】:

    R 在创建直方图时默认做了很多事情

    您可以通过以下方式打印出直方图的这些参数 分配给一个对象histinfo,然后打印:

    breaks 将为您提供 bin 宽度:

    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"
    

    【讨论】: