代码之家  ›  专栏  ›  技术社区  ›  Christian Stade-Schuldt

为柱状图分组数字

  •  2
  • Christian Stade-Schuldt  · 技术社区  · 15 年前

    我有一堆数字要用来生成标准分数的柱状图。

    因此,我计算了数字的平均值和标准差,并用这个公式将每个x归一化。

    x’=(x-平均值)/标准偏差

    结果是一个介于-4和4之间的数字。我想把结果制成图表。我正在寻找一种方法来分组,以避免到小酒吧。

    我的计划是以连续四分之一单元为中心,间隔为[-4,4],即[-4,-3.75,…,3.75,4]

    示例:0.1=>bin“0.0”,0.3=>bin“0.25”,-1.3=>bin“-1.5”

    实现这一目标的最佳方法是什么?

    2 回复  |  直到 15 年前
        1
  •  3
  •   sris    15 年前

    这里有一个不使用任何第三方库的解决方案。数字应该在数组中 vals .

    MULTIPLIER  = 0.25 
    multipliers = []
    0.step(1, MULTIPLIER) { |n| multipliers << n }
    
    histogram = Hash.new 0
    
    # find the appropriate "bin" and create the histogram
    vals.each do |val|
      # create an array with all the residuals and select the smallest
      cmp = multipliers.map { |group| [group, (group - val%1).abs] }
      bin = cmp.min { |a, b| a.last <=> b.last }.first
      histogram[val.truncate + bin] += 1
    end
    

    我认为它可以进行适当的取整。但我只是试了一下:

    vals = Array.new(10000) { (rand * 10) % 4 * (rand(2) == 0 ? 1 : -1) }
    

    分布有点歪斜,但这可能是随机数发生器的故障。

        2
  •  2
  •   Marcel Guzman    15 年前

    Rails提供了可枚举的分组方式——请参阅此处的源代码,假设您不使用Rails: http://api.rubyonrails.org/classes/Enumerable.html

    假设您的列表名为xs,则可以执行以下操作(未测试):

    bars = xs.group_by {|x| #determine bin here}
    

    然后你会得到一个散列,看起来像:

    bars = { 0 => [elements,in,first,bin], 1 => [elements,in,second,bin], etc }