Sha256: bcd0e4f1ef82aae334550a35f339b57276f424d2a9b2581b070cdb1f0ea9e9c3

Contents?: true

Size: 1.96 KB

Versions: 2

Compression:

Stored size: 1.96 KB

Contents

require "subtle/dominikh/graph"

module Dominikh
  class Chart < Graph
    attr_reader :values

    # @param [Fixnum] width The width of the chart. This corresponds
    # with the number of values-1.
    # @param [Fixnum] height The height of the chart.
    # @param [Boolean] autoscale If false, values are expected to be
    # percentage values. If true, values will be dynamically scaled
    # based on the biggest one.
    def initialize(width, height, autoscale = false)
      super(width, height)
      @values = [0]
      @autoscale = autoscale
      if autoscale
        @biggest_value = 0
      end
    end

    # @return [Number] The most current value
    def value
      @values.first
    end

    # Allows setting an array of values. If too many values are
    # provied, the array will be truncated
    #
    # @param [Array<Numeric>] arr An array of numbers
    # @return [Array] The array of values, possibly truncated
    def values=(arr)
      @values = arr[0..@icon.width-1]
      max = @values.max
      @biggest_value = max if max > @biggest_value
      render
      @values
    end

    # Adds a new value, potentially removing the oldest one if the max
    # number of values is exceeded
    #
    # @param [Numeric] value A value to store
    # @return The value
    def push(value)
      @biggest_value = value if @autoscale && value > @biggest_value
      @values.unshift(value)

      # only store as many values as we can display
      if @values.size > width
        @values.pop
      end

      render
      value
    end

    def render
      super
      if @autoscale
        factor = height.to_f / @biggest_value
      end

      @values.each_with_index do |value, index|
        x = width - 1 - index
        if !@autoscale
          y = ((height / 100.0) * value).round
        else
          y = (factor*value).round
        end

        # draw the bar
        height.downto(height - 1 - y) do |one_y|
          draw(x, one_y)
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
subtle-graph-0.0.3 lib/subtle/dominikh/graph/chart.rb
subtle-graph-0.0.2 lib/subtle/dominikh/graph/chart.rb