red-data-tools / unicode_plot.rb

Plot your data by Unicode characters
MIT License
246 stars 12 forks source link

Histogram with two values causes failure #24

Closed schneems closed 4 years ago

schneems commented 4 years ago
# fails
require 'stringio'
require 'unicode_plot'

values = [1, 2]

plot = UnicodePlot.histogram(values, title: "Histogram")
plot.render($stdout)

Gives me:

Traceback (most recent call last):
        7: from /Users/rschneeman/.rubies/ruby-2.7.0/bin/irb:23:in `<main>'
        6: from /Users/rschneeman/.rubies/ruby-2.7.0/bin/irb:23:in `load'
        5: from /Users/rschneeman/.rubies/ruby-2.7.0/lib/ruby/gems/2.7.0/gems/irb-1.2.1/exe/irb:11:in `<top (required)>'
        4: from (irb):5
        3: from /Users/rschneeman/.gem/ruby/2.7.0/gems/unicode_plot-0.0.3/lib/unicode_plot/histogram.rb:42:in `histogram'
        2: from /Users/rschneeman/.gem/ruby/2.7.0/gems/unicode_plot-0.0.3/lib/unicode_plot/barplot.rb:103:in `barplot'
        1: from /Users/rschneeman/.gem/ruby/2.7.0/gems/unicode_plot-0.0.3/lib/unicode_plot/barplot.rb:103:in `min'
ArgumentError (comparison of NilClass with 1 failed)

Ruby 2.7.0

It looks like when values get passed to BarChart the arguments include a nil:

[["\e[90m[\e[0m1.0\e[90m, \e[0m2.0\e[90m)\e[0m", "\e[90m[\e[0m2.0\e[90m, \e[0m3.0\e[90m)\e[0m", "\e[90m[\e[0m3.0\e[90m, \e[0m4.0\e[90m)\e[0m"], [1, nil, 1]]

Notice the nil in the debug output.

This doesn't appear to happen when rendering a histogram with 1 or 3 items.

Update: It looks like this only happens on specific input numbers, for example this works with no error:

# works 
require 'stringio'
require 'unicode_plot'

values = [0.017029, 0.018725]

plot = UnicodePlot.histogram(values, title: "Histogram")
plot.render($stdout)

I'm guessing the edge condition has something to do with the calculated bins.

mrkn commented 4 years ago

@schneems I released the version 0.0.4. Please use it.

$ irb -Ilib -runicode_plot --simple-prompt
>> UnicodePlot.histogram([1, 2], title: "Histogram").render
                              Histogram
              ┌                                        ┐
   [1.0, 1.5) ┤▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 1
   [1.5, 2.0) ┤ 0
   [2.0, 2.5) ┤▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 1
              └                                        ┘
                              Frequency
=> nil
>>
schneems commented 4 years ago

Thank you! -- Richard Schneeman https://www.schneems.com