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:

  • This assumes that the Crumpet object has a Rails created_on field
  • The if day % 3 == 0 just spaces out the date labels a bit
  • This code can go right into a controller and, if you put it in an action called crumpetchartaction, can be called from a view with something like
  • If you're using Gruff, consider donating a few bucks to Geoffrey for encouragement's sake. Yup, I did :-)

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:

  • ImageMagick (or RMagick? not sure) wants to default to the font ariel.ttf. This didn't come with Fedora Core, but I got it by downloading and installing msttcorefonts-1.2-3.src.rpm.
  • Of course, that's just a source RPM, so I cd /usr/src/redhat/SPECS and did a rpmbuild --ba msttcorefonts.spec.
  • Oops, it needs cabextract, so I got that from here; I got the cabextract-1.1-1.i386.rpm file and installed it.
  • Back to /usr/src/redhat/SPECS, running rpmbuild again, but it can't download the fonts from the SourceForge mirror. Edited the msttcorefonts.spec file, changed the first character of line 10 from a "#" to a "%" - in other words, switched the SourceForge mirror selection from the telia mirror to the umn mirror. Now the rpmbuild command works fine, it builds the RPM, yay!
  • Now do a rpm -i /usr/src/redhat/RPMS/noarch/msttcorefonts-1.2-3.noarch.rpm, that installs the fonts. But ImageMagick still couldn't find them, so I did a mkdir /usr/share/fonts/default/TrueType and a cp /usr/X11R6/lib/X11/fonts/msttcoreconts/*.ttf /usr/share/fonts/default/TrueType/. After that... success!