【问题标题】:Exact number of bins in Histogram in RR中直方图中的确切bin数
【发布时间】:2013-05-31 16:17:52
【问题描述】:

我在 R 中制作直方图时遇到问题。问题是我告诉它制作 5 个 bin,但它制作了 4 个,我告诉它制作 5 个,它制作了 8 个。

data <- c(5.28, 14.64, 37.25, 78.9, 44.92, 8.96, 19.22, 34.81, 33.89, 24.28, 6.5, 4.32, 2.77, 17.6, 33.26, 52.78, 5.98, 22.48, 20.11, 65.74, 35.73, 56.95, 30.61, 29.82);

hist(data, nclass = 5,freq=FALSE,col="orange",main="Histogram",xlab="x",ylab="f(x)",yaxs="i",xaxs="i")

关于如何解决它的任何想法?

【问题讨论】:

    标签: r statistics histogram


    【解决方案1】:

    指定为nclass 参数的整数用作建议:

    这个数字只是一个建议

    另一种解决方案是将您的向量cut 分成指定数量的组并绘制结果:

    plot(cut(data, breaks = 4))
    

    【讨论】:

      【解决方案2】:

      使用中断参数:

      hist(data, breaks=seq(0,80,l=6),
             freq=FALSE,col="orange",main="Histogram",
             xlab="x",ylab="f(x)",yaxs="i",xaxs="i")
      

      【讨论】:

      • 谢谢!这也非常适合比较频率分布或 PDF。
      【解决方案3】:

      如果你不反对使用基本图形以外的东西,总有 ggplot2 做事的方式:

      库(ggplot2)

      数据

          ggplot(data, aes(x=x))+
            geom_histogram(binwidth=18,color="black", fill="grey")+
            scale_x_continuous(breaks=c(0,20,40,60,80)
      

      ggplot2 有很好的文档:https://ggplot2.tidyverse.org/

      对于直方图的具体示例:https://ggplot2.tidyverse.org/reference/geom_histogram.html

      【讨论】:

        【解决方案4】:

        基于 Rob Hyndman 的回答:

        也许更通用的解决方案是考虑数据的最小值和最大值,以及中断数 = number_of_bins+1。

        hist(data,breaks=seq(min(data),max(data),l=number_of_bins+1), 
             freq=FALSE,col="orange",
             main="Histogram",xlab="x",ylab="f(x)",yaxs="i",xaxs="i")
        

        【讨论】:

          【解决方案5】:

          我喜欢对我的数据点非常准确:

          hist(data,breaks = seq(min(data),max(data),by=((max(data) - min(data))/(length(data)-1))))
          

          这应该会在几乎没有手动输入的情况下自动化该过程。

          【讨论】:

          • by= 参数应该除以长度(数据),而不是长度(数据)-1
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-13
          相关资源
          最近更新 更多