Simple Google Pie Chart Graph in Rails

Although there are many comprehensive libraries out there for google graphs in Rails, all we needed was a quick and simple pie chart. Here’s what we came up with:


module ApplicationHelper
  def google_pie_chart(data, options = {})
    options[:width] ||= 250
    options[:height] ||= 100
    options[:colors] = %w(0DB2AC F5DD7E FC8D4D FC694D FABA32 704948 968144 C08FBC ADD97E)
    dt = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-."
    options[:divisor] ||= 1

    while (data.map { |k,v| v }.max / options[:divisor] >= 4096) do
      options[:divisor] *= 10
    end

    opts = {
      :cht => "p",
      :chd => "e:#{data.map{|k,v|v=v/options[:divisor];dt[v/64..v/64]+dt[v%64..v%64]}}",
      :chl => "#{data.map { |k,v| CGI::escape(k + " (#{v})")}.join('|')}",
      :chs => "#{options[:width]}x#{options[:height]}",
      :chco => options[:colors].slice(0, data.length).join(',')
    }

    image_tag("http://chart.apis.google.com/chart?#{opts.map{|k,v|"#{k}=#{v}"}.join('&')}")
  rescue
  end
end

Here’s an example of how to use it:


<%=google_pie_chart([["Very Liberal", 8], ["Liberal", 22], ["Moderate", 9], ["Conservative", 4], ["Very Conservative", 1]], :width => 626, :height => 300) %>

And what it renders:

2 Comments

  1. matt says:

    this is pretty nice, cheers :)

  2. Awesome work thanks a bunch!