Skip to content

Instantly share code, notes, and snippets.

@erkal
Last active November 25, 2023 15:45
Show Gist options
  • Save erkal/9746513 to your computer and use it in GitHub Desktop.
Save erkal/9746513 to your computer and use it in GitHub Desktop.
Random Graph Generator

Random Graph Generator

Click anywhere to generate a new random graph.

  • The nodes are colored by the number of their neighbors.
  • Nodes with higher number of neighbours are bigger.
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.link {stroke: black;}
.node {stroke: white; stroke-width: 3px;}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
var width = 960, height = 500, colors = d3.scale.category10();
var n = 20, // number of nodes
m = 22, // number of links
charge = -1000;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.on("mousedown", create);
create();
function create () {
svg.selectAll(".link, .node").remove();
randomGraph(n, m, charge);
}
function randomGraph (n, m, charge) { //creates a random graph on n nodes and m links
var nodes = d3.range(n).map(Object),
list = randomChoose(unorderedPairs(d3.range(n)), m),
links = list.map(function (a) { return {source: a[0], target: a[1]} });
var force = d3.layout.force()
.size([width, height])
.nodes(nodes)
.links(links)
.charge(charge)
.on("tick", tick)
.start();
var svgLinks = svg.selectAll(".link").data(links)
.enter().append("line")
.attr("class", "link");
var svgNodes = svg.selectAll(".node").data(nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 3)
.style("fill", "white");
svgNodes.transition().duration(800)
.attr("r", function (d) { return 3 + 3 * d.weight })
.style("fill", function (d) { return colors(d.weight) });
svgLinks.transition().duration(800)
.style("stroke-width", 3);
function tick () {
svgNodes
.attr("cx", function(d) { return d.x })
.attr("cy", function(d) { return d.y });
svgLinks
.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 });
}
}
function randomChoose (s, k) { // returns a random k element subset of s
var a = [], i = -1, j;
while (++i < k) {
j = Math.floor(Math.random() * s.length);
a.push(s.splice(j, 1)[0]);
};
return a;
}
function unorderedPairs (s) { // returns the list of all unordered pairs from s
var i = -1, a = [], j;
while (++i < s.length) {
j = i;
while (++j < s.length) a.push([s[i],s[j]])
};
return a;
}
</script>
@peyremorgan
Copy link

peyremorgan commented Aug 31, 2018

Hello,

this gist appears to have no license. Maybe consider adding one?

Thanks,
~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment