Skip to content

Instantly share code, notes, and snippets.

@twedl
Last active January 6, 2016 13:14
Show Gist options
  • Save twedl/001d30243b82fc475142 to your computer and use it in GitHub Desktop.
Save twedl/001d30243b82fc475142 to your computer and use it in GitHub Desktop.
Erdos-Renyi Random Graph
<!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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment