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:
- Title of the chart
- A Hash of the data (the Caption for data => Array of data)
- A Hash of labels for the X axis
- Path of the final generated image
- The scale of the image from the original chart size of 700px*700px
- 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:













