Skip to content

Instantly share code, notes, and snippets.

@dandelany
Created December 5, 2014 06:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dandelany/f85462678ca3579e682d to your computer and use it in GitHub Desktop.
Save dandelany/f85462678ca3579e682d to your computer and use it in GitHub Desktop.
graph test
var _ = require('underscore');
var $ = require('jquery');
var d3 = require('d3');
var testData = {
"nodes":[
{"name":"Myriel","group":1},
{"name":"Napoleon","group":1}
],
"links":[
{"source":1,"target":0,"value":1}
]
};
window.testData = testData;
var width = 1100,
height = 700;
var color = d3.scale.category20();
var force = d3.layout.force()
.charge(-20)
.linkDistance(10)
.size([width, height])
.nodes(testData.nodes)
.links(testData.links);
var svg = d3.select("#d3-example").append("svg")
.attr("width", width)
.attr("height", height);
var link = svg.selectAll(".link")
var node = svg.selectAll(".node");
node.append("title")
.text(function(d) { return d.name; });
force.on("tick", function() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
function render() {
node = node.data(testData.nodes);
node.enter().append("circle")
.attr("class", "node")
.attr("r", 5)
.style("fill", function(d) { return color(d.group); })
.call(force.drag);
node.exit().remove();
link = link.data(testData.links);
link.enter().append("line")
.attr("class", "link")
.style("stroke-width", function(d) { return Math.sqrt(d.value); });
link.exit().remove();
force.start();
}
var limit = 500, i = 0;
var addNodesInterval = setInterval(function() {
testData.nodes.push({"name":"Myriel","group":1});
testData.links.push({
source: Math.floor(Math.random() * (testData.nodes.length - 1)),
target: Math.floor(Math.random() * (testData.nodes.length - 1))
});
render();
force.start();
i++;
if(i >= limit) clearInterval(addNodesInterval);
}, 100);
render();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment