On Friday, Google released their Charts API. You pass your data in a URL, google give you a nice graph back.

The hard part is encoding you’re raw data, into one of Google’s three formats. So I thought I’d help all out!

All of the methods take an array of integers and the maximum value of those integers. It then returns the data in the relevant format.


my_data = [1,2,3,4,5]
my_max_value = my_data.sort.last
simple_encode(my_data, my_max_value)
text_encode(my_data, my_max_value)
extended_encode(my_data, my_max_value)

Simple Encoding

Documentation


    def simple_encode(data_arr, max_value)
      simple_encoding = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
      # Douglas F Shearer 2007
      # http://douglasfshearer.com/blog/ruby-google-charts-api-data-encoding
      data = ''
      data_arr.each do |value|
        if value.is_a?(Integer) && value >= 0
          data << simple_encoding[((simple_encoding.length-1).to_f * value.to_f / max_value.to_f).to_i]
        else
          data << '_'
        end
      end
      data
    end

Text Encoding

Documentation


    def text_encode(data_arr, max_value)
      # Douglas F Shearer 2007
      # http://douglasfshearer.com/blog/ruby-google-charts-api-data-encoding
      data = ''
      data_arr.each do |value|
        if value.is_a?(Integer) && value >= 0
          data << ((999.0 * value.to_f / max_value.to_f).round/10.to_f).to_s
        else
          data << '-1'
        end
        data << ','
      end
      data.chop
    end

Extended Encoding

Documentation


    def extended_encode(data_arr, max_value)
      # Douglas F Shearer 2007
      # http://douglasfshearer.com/blog/ruby-google-charts-api-data-encoding
      characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.'.split(//)
      data = ''
      data_arr.each do |value|
        if value.is_a?(Integer) && value >= 0
          new_value = ((4095 * value.to_f / max_value.to_f).to_i)
          sixtyfours = new_value/64
          units = new_value%64
          p '64:' + sixtyfours.to_s
          p 'units: ' + units.to_s
          data << characters[sixtyfours] + characters[units]
        else
          data << '__'
        end
      end
      data
    end

A Plugin

I may at some point release a ruby wrapper for this as a plugin. Currently I have a fairly good, tested prototype that covers most of the features for line and bar charts. More will be added as I need it, but release may not be imminent.

Any errata or comments for the above should be emailed to my usual address, or just leave a comment below.