Forked from Ananda's Pen force layout demo.
Created
July 18, 2015 17:48
-
-
Save anonymous/9f23538c1c5e0a39233a to your computer and use it in GitHub Desktop.
force layout demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Width and height | |
var w = 700; | |
var h = 500; | |
//Original data | |
var dataset = { | |
nodes: [ | |
{ name: "Adam" }, | |
{ name: "Bob" }, | |
{ name: "Carrie" }, | |
{ name: "Donovan" }, | |
{ name: "Edward" }, | |
{ name: "Felicity" }, | |
{ name: "George" }, | |
{ name: "Hannah" }, | |
{ name: "Iris" }, | |
{ name: "Jerry" } | |
], | |
edges: [ | |
{ source: 0, target: 1 }, | |
{ source: 0, target: 2 }, | |
{ source: 0, target: 3 }, | |
{ source: 0, target: 4 }, | |
{ source: 0, target: 5 }, | |
{ source: 0, target: 9 }, | |
{ source: 1, target: 5 }, | |
{ source: 2, target: 5 }, | |
{ source: 2, target: 5 }, | |
{ source: 3, target: 4 }, | |
{ source: 5, target: 8 }, | |
{ source: 5, target: 9 }, | |
{ source: 6, target: 7 }, | |
{ source: 7, target: 8 }, | |
{ source: 8, target: 9 } | |
] | |
}; | |
var force = d3.layout.force() | |
.nodes(dataset.nodes) | |
.links(dataset.edges) | |
.size([w, h]) | |
.linkDistance([100]) | |
.charge([-300]) | |
.start(); | |
//Easy colors accessible via a 10-step ordinal scale | |
var colors = d3.scale.category10(); | |
//Create SVG element | |
var svg = d3.select("body") | |
.append("svg") | |
.attr("width", w) | |
.attr("height", h); | |
var edges = svg.selectAll("line") | |
.data(dataset.edges) | |
.enter() | |
.append("line") | |
.style("stroke", "#ccc") | |
.style("stroke-width", 1); | |
var nodes = svg.selectAll("circle") | |
.data(dataset.nodes) | |
.enter() | |
.append("circle") | |
.attr("r", 16) | |
.style("fill", function(d, i) { | |
return colors(i); | |
}) | |
.call(force.drag); | |
force.on("tick", function() { | |
edges.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; }); | |
nodes.attr("cx", function(d) { return d.x; }) .attr("cy", function(d) { return d.y; }); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment