Skip to content

Instantly share code, notes, and snippets.

@twedl
Last active January 7, 2016 03:27
Show Gist options
  • Save twedl/7ad1c5208dbecb76732e to your computer and use it in GitHub Desktop.
Save twedl/7ad1c5208dbecb76732e to your computer and use it in GitHub Desktop.
Dynamic Erdos-Renyi Graph

Visualize an Erdos-Renyi random graph, dynamically. (That is, the visualization is dynamic, not the graph.)

Some resources: Many examples from Mike Bostock and D3 Noob, and here.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.node {
stroke: #fff;
stroke-width: 1.5px;
}
.link {
stroke: #000;
stroke-opacity: 1;
}
</style>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
<script>
var nodes=[], //[{ "id": 0 }],
links=[];
var width = 650,
height = 550;
var N=100; // nodes.
var p=0.005; //Math.log(N)/N/2; // probability of edge.
for (i = 0; i < N; i++) {
nodes.push({"id": i});
}
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var force = d3.layout.force()
.nodes(nodes)
.links(links)
.charge(-50)
.linkDistance(30)
.size([width, height])
.on("tick", tick);
var link = svg.selectAll(".link");
link.data(links)
.enter().append("line")
.attr("class", "link");
var node = svg.selectAll(".node");
function linkStart() {
console.log(force.links().push({source: i, target: j}));
link = link.data(force.links(), function(d) { return d.source.id + "-" + d.target.id; });
link.enter().append("line").attr("class","link"); //.insert("line", ".node").attr("class", "link");
link.exit().remove();
force.start();
}
function nodeStart() {
node = node.data(force.nodes(), function(d) { return d.id;});
node.enter().append("circle").attr("class", function(d) {
return "node" + d.id;
}).attr("r", 5);
node.exit().remove();
force.start();
}
function tick() {
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; });
}
var i=0,
j=0;
function update() {
if (i+1==N & j+1==N) {
clearInterval(int);
}
if (j+1==N) {
j=0;
i++;
}
else {
j++;
}
if (i!=j & Math.random() < p) {
linkStart();
}
}
nodeStart();
var int = setInterval(update, 0);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment