Visualize an Erdos-Renyi random graph.
Some resources: Many examples from Mike Bostock and D3 Noob, and here.
Visualize an Erdos-Renyi random 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: #999; | |
stroke-opacity: .6; | |
} | |
</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 = 960, | |
height = 500; | |
var color = d3.scale.category20(); | |
var force = d3.layout.force() | |
.charge(-50) | |
.linkDistance(30) | |
.size([width, height]); | |
var svg = d3.select("body").append("svg") | |
.attr("width", width) | |
.attr("height", height); | |
// Create nodes here. | |
var N=100; | |
var p=0.005; //Math.log(N)/N; //0.005; | |
for (i = 0; i < N; i++) { | |
nodes.push({"id": i}); | |
} | |
for (i=0; i < N; i++ ) { | |
for (j=0; j < N; j++) { | |
var x=Math.random(); | |
if (x < p) { | |
console.log(x); | |
links.push({source: i, target: j}); | |
} | |
} | |
} | |
force | |
.nodes(nodes) | |
.links(links) | |
.start(); | |
var link = svg.selectAll(".link") | |
.data(links) | |
.enter().append("line") | |
.attr("class", "link"); | |
var node = svg.selectAll(".node") | |
.data(nodes) | |
.enter().append("circle") | |
.attr("class", "node") | |
.attr("r", 5) | |
.call(force.drag); | |
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; }); | |
}); | |
</script> |