Here’s an interactive force layout graph using D3 which allows us to position elements in a way that would be difficult to achieve using other means. Rather than simply going over the code and attaching an image of the result, I wanted to embed the D3 code into the Jekyll markdown file to make it interactive.
To start with, add the following to your _layouts/post.html file within the header tag. This will add D3 support to the markdown. Make sure you do not have d3 source code location mentioned within the script tag of your actual code - this may create version conflicts.
This is what the skeleton will look like. Note that we do not have a body tag. So if you append your SVG element to the body tag, your chart will not display. Instead create a div element before your script and append your SVG to this.
I was having some trouble linking to an external file so in this case, the data is inside the javascript file - or script tag of html file - itself in a JSON format. This is a list of dictionaries where each dict has a source, target and value key.
Get the distinct nodes by iterating over the links data. We have added a D3 force function with a charge which simulates electrostatic effects across all nodes - it is negative since we want a repulsing force. We also add a callback function tick for every time the simulation iterates or when user interacts with the chart.
Create the link paths by binding the data to the path> SVG element which is the generic element to define a shape. The seemingly arbitrary numbers for the d attribute are defining the curvy lines between our nodes.
The color of the link is set based on the ‘value’ field.
We define the D3 nodes and append to circle elements. We allow the nodes to be dragged by the user and also add a functionality to fix the nodes in place when double-clicked.
Finally define the tick function - this should update cordinates of the node and text labels. dx and dy are relative positiions of text to the nodes.
We have used D3 to create an interactive force directed layout graph with additional customizations. Hopefully this has convinced you to harness the visualization power of D3 for your next analysis!
This programming assignment was submitted as coursework for CSE6242 Data and Visual Analytics (Fall 2016), Georgia Tech College of Computing.