Class: Histogram

Inherits:
Object
  • Object
show all
Defined in:
lib/histogram.rb,
lib/histogram/version.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =
"0.1.1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(values) ⇒ Histogram

Returns a new instance of Histogram.



13
14
15
16
17
# File 'lib/histogram.rb', line 13

def initialize(values)
  @values = values
  @bin_count = BinCounter.evaluate(values)
  @bin_packer = BinPacker.new(@bin_count, values.min, values.max)
end

Instance Attribute Details

#bin_countObject (readonly)

Returns the value of attribute bin_count.



11
12
13
# File 'lib/histogram.rb', line 11

def bin_count
  @bin_count
end

Instance Method Details

#bin_widthObject



19
20
21
# File 'lib/histogram.rb', line 19

def bin_width
  @bin_packer.bin_width
end

#binsObject



23
24
25
# File 'lib/histogram.rb', line 23

def bins
  @bins ||= @bin_packer.bins(values)
end

#render(title: nil, precision: 2, border: Terminal::Table::UnicodeBorder.new) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/histogram.rb', line 27

def render(title: nil, precision: 2, border: Terminal::Table::UnicodeBorder.new)
  largest_bin = bins.max_by(&:count).count
  max_marker_count = [largest_bin, 12].min
  marker_width = largest_bin / max_marker_count

  rows = max_marker_count.times.map do |y|
    bins.size.times.map do |x|
      value = if (bins[x].count / marker_width.to_f).ceil > y
        "x"
      else
        ""
      end
      { value: value, alignment: :center }
    end
  end.reverse
  rows << bins.map { |bin| "(#{bin.count})" }

  border.top = false
  border.left = false
  border.right = false
  border.data[:y] = " "
  border.data[:n] = border.data[:nx]
  border.data[:ai] = border.data[:ax]
  border.data[:s] = border.data[:sx]

  headings = bins.map do |bin|
    min, max = bin.range.minmax
    if min == max
      min.to_s
    else
      "#{min.round(precision)}-#{max.round(precision)}"
    end
  end
  options = {
    headings: headings,
    rows: rows,
    style: {
      border: border,
    },
  }
  options[:title] = title if title

  output = Terminal::Table.new(**options).to_s

  lines = output.lines
  lines.delete_at(1) # delete header seperator
  header = if title
    lines.delete_at(1)
  else
    lines.shift
  end
  totals = lines.delete_at(-2)
  lines.last << "\n"
  lines << header
  lines << totals.chomp
  lines.join
end