Rendering google style pie chart in your rails app
5 Mar 2009Google has some of the best charts on the web. If you ever wanted to have cool pie charts like google here is a simple way to do it. Simply add the following to your application_helper.rb file.
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
Once you have that in then in your view its as simple as below to render a nice pie chart. Go ahead have a piece.
<%= google_pie_chart([["Rails",80],[".Net",10],["Java",10]) %>