Test your code D3 with Jsfiddle with JSON file, CSV, TSV present on GitHub

D3_github_jsFiddle

Introduction

Lately I often have to propose a development environment where you can easily test the Javascript code needed to produce graphs and data representation. Personally I make use of Aptana IDE as a development environment and use WAMP (for Windows) and LAMP (for Linux).. But generally during the various tutorials, articles and presentations I prefer to refer to Jsfiddle: An online environment where you can test and save in real time the JavaScript code also defining its CSS declarations and HTML tags.

Aptana IDE
Fig. 1: Aptana IDE Studio

But who makes use of jsfiddle, and especially does it to test various examples of the D3 library, will soon find a problem that is not so trivial to overcome. D3 often makes use of external files (JSON, CSV, TSV, etc.) to load data that will then be represented by a graph, but now jsfiddle at the present time does not include the import of external files.

Since Jsfiddle is an online environment, there would be no better answer to this issue than to upload data files stored within GitHub. So we have a “cloud” environment in which both the code, and the data that even the test environment itself, are made available to all those who have a browser, without worrying about installing a Web Server, a development environment Like Aptana, it also avoids copying huge files containing countless lines of data and code.

But we see in more detail all these aspects.

JsFiddle

Jsfiddle is an online application that allows developers to quickly and separately manage the 3 basic elements on which WEB programming is based:

  • Html
  • Javascript
  • Css
Jsfiddle Workspace
Fig. 2: Jsfiddle

By writing separately the three code parts of a generic HTML page you can test in real time what you are writing, all in the same page. In addition the results of our work can then be saved for later use, and even shared on the net.

In fact it is always easier to find on the net references and links to examples present on Jsfiddle. This makes it particularly suitable for the authors of tutorials and examples that use JavaScript code. By copying the link of a given example developed on Jsfiddle, you will allow the reader of a tutorial to see in real time the result of what is being described. But not only that, the reader can test it, executing it and modifying it in turn, so as to better understand the code described in an article.

Example: The circular dendrogram on Jsfiddle

In the example discussed in the article the circular dendrograms, the function D3. JSON () loads the data structure contained within an external JSON file. This is usually the usual and normal practice for the development of a Web page uploaded to a Web Server. While if di makes use of jsfiddle to test the code described in the article you need to make some minor changes.

The simplest approach is what we generally find in all the jsfiddle examples that I found browsing here and there on the net. This approach is to define the contents of the JSON file within a variable defined within the Jsfiddle pages.

In our case, (see the example directly on Jsfiddle) will be to define the JSON structure of the Dendrogram as an object in the variable root. (Don’t forget the semicolon at the end!!!)

var root = {   "name": "root",   
               "children": [     
                     {"name": "parent A",        
                      "children": [             
                           {"name": "child A1"},             
                           {"name": "child A2"},             
                           {"name": "child A3"},             
                           {"name": "child A4"},             
                           {"name": "child A5"},             
                           {"name": "child A6"}        
                      ]     },
                      {"name": "parent B",        
                       "children": [             
                           {"name": "child B1"},             
                           {"name": "child B2"},             
                           {"name": "child B3"},             
                           {"name": "child B4"},             
                           {"name": "child B5"},             
                           {"name": "child B6"},             
                           {"name": "child B7"},             
                           {"name": "child B8"}        
                       ]     },
                       {"name": "parent C",         
                        "children": [             
                           {"name": "child C1"},             
                           {"name": "child C2"},             
                           {"name": "child C3"},             
                           {"name": "child C4"}         
                       ]     }     
] };

Also you will need to delete (or comment) The call to the function D3. JSON () and the trailing brace.

D3. JSON ("DENDROGRAM02. JSON", function (error, root) { 
...
//});

Eventually the result on the Jsfiddle page will be identical to what you would have on any browser.

JsFiddle_dendrogram
Fig. 3: our example on Jsfiddle

Github

GitHub-logo

Creating an online Repository on GitHub

From the site of GitHub.com you can create a new repository

Creating your local repository with Git

Now, this series of operations will be done from the command line. You create a directory that will be the local version of the repository that we are going to create.

> mkdir D3. Examples

Within it you launch the command initialization of Git

> CD ∼/d3.examples

> git Init

Within this directory, we copy the JSON file containing the data structure of the dendrogram02. JSON Dendrogram. We then report to git the newly copied file within the local repository.

> git add dendrogram02. JSON

Now it’s time to make a commit

> git commit-M “Add first JSON”

Now you need to connect the local repository to the one created on GitHub

> git remote Add Origin https://github.com/meccanismocomplesso/d3.examples.git

If instead we want to modify an existing connection:

> git remote set-url Origin https://github.com/meccanismocomplesso/d3.examples.git

If you want to get a list of the remote sources of your local repository, type the following command

> git remote-V

Finally to upload the file from the local repository to the one on GitHub, we write:

> git push-U Origin Master

Just out of curiosity, if we needed to remove a file from GitHub, before we removed it from the local repository,

> git rm file. JSON

And then we re-execute the previous commit and upload operations

> git commit-M “Remove JSON”

> git push-U Origin Master

References on the net

To solve the need to read data files stored within GitHub using Jsfiddle I referred to the example of Zalun:

GitHub: Https://github.com/zalun/jsFiddleGithubDemo/tree/master/Demo

Jsfiddle: http://jsfiddle.net/gh/get/mootools/1.2/zalun/jsFiddleGithubDemo/tree/master/Demo/

That has developed a good example to understand the underlying mechanisms of data transfer between GitHub and Jsfiddle.

But above all, the example of Lordbaco proved to be of fundamental importance for the final realization of the example covered in this article.

Jsfiddle: http://jsfiddle.net/lordbaco/8KDg6/

Example: The circular dendrogram with the JSON file on GitHub

From the previous examples, the final step is to create an example with the D3 library that actually makes use of JSON data previously stored by me in GitHub.

GitHub: Https://github.com/meccanismocomplesso/d3.examples

Jsfiddle: http://jsfiddle.net/meccanismocomplesso/yLkyt8ow/

Here’s the code:

var radius = 250; 
var margin = 120; 
var angle = 360; 
var root; 
var cluster = d3.layout.cluster()   
     .size([angle, radius-margin]);    
var diagonal = d3.svg.diagonal.radial()   
     .projection (function(d) { return [d.y, d.x / 180* Math.PI];});  
var svg = d3.select("body").append("svg")   
     .attr("width",2*radius)   
     .attr("height",2*radius)   
     .append("g")   
     .attr("transform","translate("+radius + "," + radius + ")"); 
var url = '/gh/get/response.json/meccanismocomplesso/d3.examples/tree/master/';

d3.xhr(url)     
    .header("X-Requested-With", "XMLHttpRequest")     
    .header("Content-Type", "application/x-www-form-urlencoded")    
    .post("delay=1", function (error, request) {     
          if (error) return console.warn(error.responseText);     
          root =  jQuery.parseJSON( request.responseText); 
     //});            
     //d3.json("dendrogram02.json", function(error, root){   
     var nodes = cluster.nodes(root);   
     var links = cluster.links(nodes);               
     var link = svg.selectAll(".link")   
         .data(links)   
         .enter().append("path")  
         .attr("class","link")   
         .attr("d", diagonal);           
     var node = svg.selectAll(".node")   
         .data(nodes)   
         .enter().append("g")   
         .attr("class","node")  
         .attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; });    
      node.append("circle")   
         .attr("r", 4.5);    
      node.append("text")  
         .attr("dy", ".31em")  
         .attr("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; })  
         .attr("transform", function(d) { return d.x < 180 ? "translate(8)" : "rotate(180)translate(-8)"; })  
         .text(function(d) { return d.name; });  
});

The result is the same as the previous one but this time you can load any JSON file on GitHub.

JsFiddle_dendrogram_with_json

 Conclusions

The preceding example can also be extended immediately for datasets contained in CSV and TSV files. The mechanism is almost the same.

Leave a Reply