Friday, September 5, 2014

Word cloud

D3 library provides a lot fun ways to visualize one's data. I came across a great word-cloud library by Jason Davies, and I wanted to implement this visualization in my Rails app.

In order to do that, you first need to add d3-rails gem to your Gemfile, and //=require d3 to application.js (I always forget to restart the server at this point, and the app complains it can't find D3). You should then add d3.layout.cloud.js (downloaded from here) to the vendor/assets/javascripts directory. Finally, don't forget to add //= require d3.layout.cloud in application.js as well.

If you copy and paste example code (provided with Davies' library), it should work straight away. However, I wanted to see if I could read a static JSON file with word data instead of using a word array like in the example.

This can be done by creating a file say 'word.json' and placing it in the public directory so Rails has access to it. D3.layout.cloud requires such attributes as text and size, so the JSON file should look like this:

[
  { "text":"word1", "size":1 },
  { "text":"word2", "size":2 },
  { "text":"word3", "size":3 },
   .....
]


The file and its data can then be accessed as follows:

d3.json("/word.json", function(data){

   d3.layout.cloud().size([200,200]).words(data)

   ..... 

});

Additionally, I implemented a function that would redraw the graph on window.resize event. However, getting JSON data like this resulted in a slow and delayed rendering. Not quite sure whether this behavior is to be expected or whether something should have been done differently. Until a better solution, I am placing my words in an array directly in the function similar to the example.

No comments :

Post a Comment