D3:Learning:Force Directed Graph:A
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 {
stroke: #fff;
stroke-width: 1.5px;
}
.link {
stroke: #999;
stroke-opacity: .6;
}
JavaScript
//See: http://bl.ocks.org/mbostock/4062045
$(function () {
//Create a sized SVG surface within viz:
var width = 600,
height = 350;
var svg = d3.select("#viz")
.append("svg")
.attr("width", width)
.attr("height", height);
LayoutGraph(svg, width, height, parsedJson);
//d3.json("miserables.json",
});
function LayoutGraph(svg, width, height, graph) {
var color = d3.scale.category20();
//Create a force layout:
var force = d3.layout.force()
.charge(-200)
.linkDistance(100)
.size([width, height]);
//Start the layout engine, giving the nodes and vertices
//from the source data:
force
.nodes(graph.nodes)
.links(graph.links)
.start();
//Create a selection of (future) links:
var link = svg.selectAll(".link")
.data(graph.links)
//every time new link added, add an svg line of varying width:
.enter()
.append("line")
.attr("class", "link")
//use a functor to set the width to a dynamic value:
//Note that each link in the parsedData has a s, t, and value.
.style("stroke-width", function (d) {return Math.sqrt(d.value);});
var node = svg.selectAll(".node")
.data(graph.nodes)
//every time new node added to the selection, draw an svg circle:
.enter().append("circle")
.attr("class", "node")
.attr("r", 5)
//use a functor to set the width to a dynamic value:
.style("fill", function (d) {return color(d.group);})
//for each element in the selection, invoke the drag callback,
//which allows nodes to be dragged around.
.call(force.drag);
//for each node, append a functor that returns the name as a tooltip:
node.append("title")
.text(function (d) {return d.name;});
//Each time the force layout engine ticks,
//invoke a method that in turn
//iterates through every svg element in the set
...