Class: EverydayCliUtils::Histogram

Inherits:
Object
  • Object
show all
Defined in:
lib/everyday-cli-utils/safe/histogram.rb

Class Method Summary collapse

Class Method Details

.add_averages(height, ks, lines, mi, step, width) ⇒ Object



27
28
29
30
# File 'lib/everyday-cli-utils/safe/histogram.rb', line 27

def self.add_averages(height, ks, lines, mi, step, width)
  lines[height] = ' ' * width
  ks.each { |v| lines[height][((v - mi) / step).to_i] = '|' }
end

.add_graph(counts, height, lines, max_y, width) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
# File 'lib/everyday-cli-utils/safe/histogram.rb', line 15

def self.add_graph(counts, height, lines, max_y, width)
  (0...width).each { |i|
    h = ((counts[i].to_f / max_y.to_f) * height.to_f).round
    ((height - h)...height).each { |j|
      lines[j][i] = '#'
    }
    if h == 0 && counts[i] > 0
      lines[height - 1][i] = '_'
    end
  }
end

.histogram(collection, ks = nil, width = 100, height = 50) ⇒ Object



32
33
34
35
36
37
# File 'lib/everyday-cli-utils/safe/histogram.rb', line 32

def self.histogram(collection, ks = nil, width = 100, height = 50)
  counts, lines, max_y, mi, step = setup(collection, height, width)
  add_graph(counts, height, lines, max_y, width)
  add_averages(height, ks, lines, mi, step, width) unless ks.nil?
  lines
end

.setup(collection, height, width) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
# File 'lib/everyday-cli-utils/safe/histogram.rb', line 3

def self.setup(collection, height, width)
  mi     = collection.min
  ma     = collection.max
  diff   = ma - mi
  step   = diff.to_f / (width.to_f - 1)
  counts = Array.new(width, 0)
  collection.each { |v| counts[((v - mi).to_f / step.to_f).floor] += 1 }
  max_y = counts.max
  lines = Array.new(height) { ' ' * width }
  return counts, lines, max_y, mi, step
end