D3:Learning:Force Directed Graph:Collapsible
A starting point to clone and get investigating quickly.
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="viz" />
CSS
.node circle {
cursor: pointer;
stroke: #3182bd;
stroke-width: 1.5px;
}
.node text {
font: 10px sans-serif;
pointer-events: none;
text-anchor: middle;
}
line.link {
fill: none;
stroke: #9ecae1;
stroke-width: 1.5px;
}
JavaScript
//Notes:
// Src: http://bl.ocks.org/mbostock/1093130
//Notes:
// * Each dom element is using
// children to store refs to expanded children
// _children to store refs to collapsed children
//* It's using both a tree and a graph layout.
//root
var g = {
data: null,
force:null
};
$(function () {
//use a global var for the data:
g.data = data;
var width = 960,
height = 500;
//Create a sized SVG surface within viz:
var svg = d3.select("#viz")
.append("svg")
.attr("width", width)
.attr("height", height);
g.link = svg.selectAll(".link"),
g.node = svg.selectAll(".node");
//Create a graph layout engine:
g.force = d3.layout.force()
.linkDistance(80)
.charge(-120)
.gravity(0.05)
.size([width, height])
//that invokes the tick method to draw the elements in their new location:
.on("tick", tick);
//Draw the graph:
//Note that this method is invoked again
//when clicking nodes:
update();
});
//invoked once at the start,
//and again when from 'click' method
//which expands and collapses a node.
function update() {
//iterate through original nested data, and get one dimension array of nodes.
var nodes = flatten(g.data);
//Each node extracted above has a children attribute.
//from them, we can use a tree() layout function in order
//to build a links selection.
var links = d3.layout.tree().links(nodes);
// pass both of those sets to the graph layout engine, and restart it
g.force.nodes(nodes)
.links(links)
.start();
//-------------------
// create a subselection, wiring up data, using a function to define
//how it's suppossed to know what is appended/updated/exited
g.link = g.link.data(links, function (d) {return d.target.id;});
//Get rid of old links:
g.link.exit().remove();
//Build new links by adding new svg lines:
g.link
...