I got my first pull request accepted into Rails master
Adding a pie chart to a Rails application using Google Charts
Oct
09
09
Today I wanted to start adding some stats to ¿Cómo vamos?. Turns out it was very easy to do with the googlecharts gem.
Here’s the relevant code to generate a pie chart showing the percentage of solutions uploaded by each user on the site:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
module StatsHelper def pie_chart_for_solutions count = {} Solution.all.each do |solution| count[solution.user] ||= 0 count[solution.user] += 1 end total = Solution.count data = count.collect { |user, number| number } labels = count.collect do |user, number| "#{user.name} (#{total == 0 ? 0 : (100.0 * number / total).round}%)" end Gchart.pie(:data => data, :labels => labels, :size => '695x380', :theme => :thirty7signals) end end |
We cycle through all solutions and keep a counter for how many belong to each user. Then we generate a label for each portion of the pie, appending its user’s percentage to the end. Then we pass this data to the gem, and that’s it.
Here’s an example of how the generated chart looks like:
Take a look at this commit to see all the changes in context. And here’s the live stats page.