Skip to content

Instantly share code, notes, and snippets.

@jmacqueen
Last active December 27, 2015 18:59
Show Gist options
  • Save jmacqueen/7373734 to your computer and use it in GitHub Desktop.
Save jmacqueen/7373734 to your computer and use it in GitHub Desktop.
D3.js: Messy Random Graph with Force Layout

I have a particular interest in organizing graph layouts. This is a deliberately messy random starting point to experiment with organizational techniques.

If you want to interact with these D3.js gists without downloading them yourself, replace https://gist.github.com with http://bl.ocks.org to go to Mike Bostock's excellent website for running D3.js gists.

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Force Layout Link Scaling</title>
<link rel="stylesheet" href="random-force-layout.css">
<script src="http://d3js.org/d3.v3.min.js"></script>
</head>
<body>
<script>
var width = 800;
var height = 400;
var numPoints = 100;
var svg = d3.select("body").append("svg").attr("width", width).attr("height", height);
var force = d3.layout.force().size([width,height]);
var nodes = [];
for (var j=0;j<numPoints;j++){
nodes[j] = {
name: "Node " + j
};
}
var links = [];
for (j=0;j<numPoints;j++){
var src = Math.floor(Math.random() * numPoints);
var tar = Math.floor(Math.random() * numPoints);
if (tar === src) {
if (src != 0) {
tar = src - 1;
} else {
tar = 1;
}
}
links[j] = {
source: src,
target: tar
};
}
force.links(links);
var linkSelection = svg.selectAll("line").data(links);
linkSelection.enter()
.insert("line")
.classed("link", true);
force.nodes(nodes);
var nodeSelection = svg.selectAll("circle.node").data(nodes);
nodeSelection.enter()
.append("circle")
.attr("r", 5)
.classed("node", true)
.call(force.drag);
force.on("tick", function(e){
linkSelection.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;});
nodeSelection.attr("cx", function(d){return d.x;})
.attr("cy", function(d) {return d.y});
});
// Main
force.start();
</script>
</body>
</html>
body {
font-family: Helvetica,sans-serif;
}
.controls {
border-bottom: solid 1px black;
padding: 1em 5%;
}
svg {
border: solid 1px black;
margin: 1em 5%;
}
.node {
fill: lightblue;
stroke: black;
}
.link {
stroke: black;
stroke-width: 1px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment