Charts in Ruby - Using Gruff

It is very common requirement for any reporting application to be able to draw charts based on some historical and statistical data. The languages with big user community like Java have various libraries available for creating charts. But when it comes to Ruby, there are not as many or as sophisticated choices. I was looking for a library in Ruby to do this sometime back and I found Gruff. It’s a very simple and efficient library.


To install Gruff, all you need to do is:

gem install gruff

You also need to have the RMagick installed that needs the ImageMagick to be installed. You can install ImageMagick using the package manager of your Linux distribution or download it directly from ImageMagick website and install. The RMagick installation can be done by either using gem or using the native OS package manager. On my Mandriva Linux box, the gem installation kept on failing during compilation. So, I just installed it using urpmi and it worked.
I wrote a small module in Ruby to draw the line charts. This module can be included in the scripts where you need to draw the charts. This module is called charts.rb. Here is the source code for it:

The arguments for drawChart function are as follows:

  1. Title of the chart
  2. A Hash of the data (the Caption for data => Array of data)
  3. A Hash of labels for the X axis
  4. Path of the final generated image
  5. The scale of the image from the original chart size of 700px*700px
  6. An array of hex colors if you do not want to use Gruff’s default color scheme

Now, here is how you can use the chart module and the drawChart function:


That’s pretty much all the code. In the end you should have a chart generated like following:
A chart generated by Gruff

Share and Enjoy:
  • Digg
  • del.icio.us
  • description
  • Technorati
  • Reddit
  • Facebook
  • blogmarks
  • YahooMyWeb
  • Ma.gnolia

Comments (6)

Path to Ruby Scripts

Ever wondered how to set the path to some Ruby scripts you have written, so you can use them using “require”? There is a very basic solution for this problem. You need to define a system variable called RUBYLIB and point it to the directory containing your Ruby scripts. Then in your script where you want to use the library or script you created, you can simply do a “require” with the name of the script.

e.g. Supposed you created a script chart.rb in /home/foo/ruby/mylib direcory. Now, you want to use this in the app.rb located in /home/foo/ruby/scripts. Here is how you can make it work in a Linux bash environment. You could very well do this in other environments as well with minimal modifications.
In your ~/.bash_profile

export RUBYLIB=$RUBYLIB:/home/foo/ruby/mylib

and then in the app.rb script:

require 'chart'

That’s it.

Share and Enjoy:
  • Digg
  • del.icio.us
  • description
  • Technorati
  • Reddit
  • Facebook
  • blogmarks
  • YahooMyWeb
  • Ma.gnolia

Comments (1)

Next entries »