Skip to content

Instantly share code, notes, and snippets.

@lindep
Last active July 13, 2016 08:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lindep/298d3875ce871d742e006860c5b78ff7 to your computer and use it in GitHub Desktop.
Save lindep/298d3875ce871d742e006860c5b78ff7 to your computer and use it in GitHub Desktop.
Basic Force Layout v3
license: gpl-3.0

Basic Force Layout

Serves as a basis for other force layout examples.

forked from erkal's block: Basic Force Layout

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.link {
stroke: black;
stroke-width: 2px;
}
.node {
fill: steelblue;
stroke: white;
stroke-width: 2px;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
var width = 457,
height = 500,
nodes = [{},{},{},{},{}],
links = [{source: 0, target: 1}, {source: 1, target: 2}, {source: 2, target: 3}, {source: 3, target: 4}, {source: 4, target: 0}];
var force = d3.layout.force()
.size([width, height])
.nodes(nodes)
.links(links)
.linkDistance(38)
.charge(-475)
.on("tick", tick)
.start();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
svgLinks = svg.selectAll(".link").data(links)
.enter().append("line")
.attr("class", "link");
svgNodes = svg.selectAll(".node").data(nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 9)
.call(force.drag);
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 });
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment