Charts and graphs in Ruby on Rails

21 Feb 2006

Thanks to Geoffrey Grosenbach for writing the great little Gruff graphing library! It's a fine piece of work and let me create some nice graphs for the indi backend.

More specifically, I wanted to do some time based graphs. Here's some code to create a list of crumpets sold to date:

days = 5
g =
g.title = "Crumpets over the past #{days} days"
crumpets_to_date = []
labels = {}
days.downto(0) do |day|
  date_stamp = - (60*60*24*day)
  date_sql_string = date_stamp.strftime("%Y-%m-%d")
  crumpets_to_date << Crumpets.count("created_on < '#{date_sql_string}'").to_i
  labels[days-day] = date_stamp.strftime("%b %d") if day % 3 == 0
end"Crumpets Sold", crumpets_to_date)
g.labels = labels
  :disposition => 'inline',
  :type => 'image/png',
  :filename => "crumpets_over_time.png")

The graph produced looks like this:

Couple of misc notes:

There are some tricky bits in getting Gruff set up; I've seen posts on the Rails list and elsewhere from folks having problems. Here are some notes on getting the fonts set up: