Thursday, July 24, 2008

Fusion Charts with Ruby on Rails

Seasonality is an important component of forecasting, and thanks to Google Trends, we can quickly get multi-year seasonality for a category such as 'Turtlenecks'. After downloading the CSV file, I wanted to reproduce the chart from the data on our web-page.

Fusion Charts is a fantastic charting package, although so far we can only afford the free version. I will show a particular trick of extending Fusion Charts Free to manipulate the X-axis label. The time series from Google Trends had 234 weeks of data, which meant 234 labels. These ran into each other, creating an illegible axis. Also, the default mode for Fusion Charts is to display the values of the data points. With a lot of data points, these crowd the graph. The results, as seen here, are a far cry from the beautiful graphs of Google Trends.


A little bit of Ruby goes a long way to quickly fix this problem. First of all, I need to tell Fusion Charts to suppress the value on the graph. This is done by setting the showValues parameter to 0 in the xml header. I am using the excellent Builder library, where I can pass this as a key-value pair :showValues => 0. Next, I want to show the week for every 13th week. The paid version of Fusion Charts has a parameter setting for this. But for the cheapskates of the world, Ruby to the rescue again. The trick is to set the showName parameter to 0 in every thirteenth line of the xml. Finally, let's rotate the labels so they are vertically oriented, reducing the overlap. This is done by passing another key-value pair to the xml head, :rotateNames => 1. The final code to generate the xml is posted below. The new graph, after the changes, is much cleaner.


counter = 0
xml.graph (:showValues => 0, :rotateNames=> 1) do
@trend_weeks.each do tweek
counter = counter + 1
if counter.modulo(13) == 0 xml.set :name => tweek.week_date, :value => tweek.index
else
xml.set :name => tweek.week_date, :value => tweek.index, :showName => 0
end
end
end
I am still new to Ruby, and am sure there is a more idiomatic way of doing this. Please post it in the comments.
Also, it took me a very long time to get Fusion Charts to work the first time in Rails. It was mostly little mistakes that I kept making, as well as an incomplete understanding of how routes worked in the 2.0 world. I may get along to posting a full tutorial on this subject. If somebody needs to get started quickly, please contact me and I can try and help you. Happy Charting!

No comments: