red-data-tools / unicode_plot.rb

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

Inconsistent x range behaviour with dates #64

Open archiewood opened 3 months ago

archiewood commented 3 months ago

Issue

When I plot three different charts with identical y data, but transpose the x range, the x labels are incorrect, and the displayed ranges differ.

To reproduce

require 'unicode_plot'

def plot_sine_for_year(year)
  start_date = Date.new(year, 1, 1)
  x = (0..364).map { |i| start_date + i }
  y_sin = x.map { |xi| Math.sin((xi - start_date).to_f / 30 * 2 * Math::PI) }
  plot = UnicodePlot.lineplot(x, y_sin, name: "sin(x)", width: 40, height: 5, title: year.to_s)
  plot.render
end

[2020, 2021, 2022].each { |year| plot_sine_for_year(year) }

Expected behaviour

The x ranges start and finish at the same point relative to the first datapoint

OR

The x labels are the actual labels for the starting point of the axis, rather than the beginning and end of the range

Actual behaviour

The scales are all different

                        2020
      ┌────────────────────────────────────────┐       
    1 │⠀⠀⢀⢿⠀⢀⢿⠀⢀⢿⠀⢀⢿⠀⢀⢿⠀⢀⢿⠀⢀⢿⠀⢀⢿⠀⢀⢿⠀⢀⢿⠀⢀⢿⠀⢀⢿⠀⢀⠀│ sin(x)
      │⠀⠀⢸⠸⡀⢸⠸⡀⢸⠸⡀⢸⠸⡀⢸⠸⡀⢸⠸⡀⢸⠸⡀⢸⠸⡀⢸⠸⡀⢸⠸⡀⢸⠸⡀⢸⠸⡀⢸⠀│       
      │⠤⠤⠼⠤⡧⢼⠤⡧⢼⠤⡧⢼⠤⡧⢼⠤⡧⢼⠤⡧⢼⠤⡧⢼⠤⡧⢼⠤⡧⢼⠤⡧⢼⠤⡧⢼⠤⡧⢼⠤│       
      │⠀⠀⠀⠀⡇⡎⠀⡇⡎⠀⡇⡎⠀⡇⡎⠀⡇⡎⠀⡇⡎⠀⡇⡎⠀⡇⡎⠀⡇⡎⠀⡇⡎⠀⡇⡎⠀⡇⡎⠀│       
   -1 │⠀⠀⠀⠀⢱⡇⠀⢱⡇⠀⢱⡇⠀⢱⡇⠀⢱⡇⠀⢱⡇⠀⢱⡇⠀⢱⡇⠀⢱⡇⠀⢱⡇⠀⢱⡇⠀⢱⡇⠀│       
      └────────────────────────────────────────┘       
      2020-01-01                      2020-12-30
                        2021
      ┌────────────────────────────────────────┐       
    1 │⠀⠀⠀⠀⠀⠀⠀⢸⡇⠀⣷⠀⡜⡄⢰⡇⠀⣿⠀⢸⡇⠀⣷⠀⡜⡄⢰⡇⠀⣿⠀⢸⡇⠀⣷⠀⡀⠀⠀⠀│ sin(x)
      │⠀⠀⠀⠀⠀⠀⠀⡜⡇⢸⢹⠀⡇⡇⢸⢸⠀⡟⡆⡜⡇⢸⢹⠀⡇⡇⢸⢸⠀⡟⡆⡜⡇⢸⢹⠀⡇⠀⠀⠀│       
      │⠤⠤⠤⠤⠤⠤⠤⠧⢼⢼⠼⡤⡧⡧⢼⢼⢴⠥⡧⡧⢼⢼⢼⠤⡧⡧⢼⢼⢴⠥⡧⡧⢼⢼⠼⡤⡧⠤⠤⠤│       
      │⠀⠀⠀⠀⠀⠀⠀⠀⢸⢸⠀⣧⠇⢣⡇⢸⣸⠀⡇⡇⢸⢸⠀⣧⠇⢣⡇⢸⣸⠀⡇⡇⢸⢸⠀⣧⠇⠀⠀⠀│       
   -1 │⠀⠀⠀⠀⠀⠀⠀⠀⠸⡇⠀⣿⠀⢸⡇⠀⡿⠀⢣⠃⠸⡇⠀⣿⠀⢸⡇⠀⡿⠀⢣⠃⠸⡇⠀⣿⠀⠀⠀⠀│       
      └────────────────────────────────────────┘       
      2021-01-01                      2021-12-31
                        2022
      ┌────────────────────────────────────────┐       
    1 │⠀⠀⠀⠀⢰⡇⠀⣿⠀⢸⡇⠀⣷⠀⡜⡄⢰⡇⠀⣿⠀⢸⡇⠀⣷⠀⡜⡄⢰⡇⠀⣿⠀⢀⠀⠀⠀⠀⠀⠀│ sin(x)
      │⠀⠀⠀⠀⢸⢸⠀⡟⡆⡜⡇⢸⢹⠀⡇⡇⢸⢸⠀⡟⡆⡜⡇⢸⢹⠀⡇⡇⢸⢸⠀⡟⡆⡜⠀⠀⠀⠀⠀⠀│       
      │⠤⠤⠤⠤⠼⢼⢴⠥⡧⡧⢼⢼⠼⡤⡧⡧⢼⢼⢴⠥⡧⡧⢼⢼⢼⠤⡧⡧⢼⢼⢴⠥⡧⡧⠤⠤⠤⠤⠤⠤│       
      │⠀⠀⠀⠀⠀⢸⣸⠀⡇⡇⢸⢸⠀⣧⠇⢣⡇⢸⣸⠀⡇⡇⢸⢸⠀⣧⠇⢣⡇⢸⣸⠀⡇⡇⠀⠀⠀⠀⠀⠀│       
   -1 │⠀⠀⠀⠀⠀⠀⡿⠀⢣⠃⠸⡇⠀⣿⠀⢸⡇⠀⡿⠀⢣⠃⠸⡇⠀⣿⠀⢸⡇⠀⡿⠀⢣⠃⠀⠀⠀⠀⠀⠀│       
      └────────────────────────────────────────┘       
      2022-01-01                      2022-12-31

CleanShot 2024-08-12 at 19 38 57@2x

archiewood commented 3 months ago

I believe the line causing the behaviour is here

https://github.com/red-data-tools/unicode_plot.rb/blob/caa4c5e055c44c2e48c317656ed0096f9a54b566/lib/unicode_plot/lineplot.rb#L61

Despite the plot function increasing range so the xmin and xmax are a nice "rounded" number that divides by 10 (not sensible behaviour for dates), the x labels being used are the ends of the date range the user supplies