Skip to content

Instantly share code, notes, and snippets.

@katsumitakano
Last active August 29, 2015 13:57
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 katsumitakano/9645721 to your computer and use it in GitHub Desktop.
Save katsumitakano/9645721 to your computer and use it in GitHub Desktop.
Force Layout
<!doctype html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>force-layout</title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<style>
.node {
stroke: #fff;
stroke-width: 1.5px;
}
.link {
stroke: #999;
stroke-opacity: .6;
}
</style>
</head>
<body>
<script>
var dataset = {
nodes: [
{id: 0, name: "Taro", sex: "M"},
{id: 1, name: "Ken", sex: "M"},
{id: 2, name: "Hana", sex: "F"},
{id: 3, name: "Mike" ,sex: "M"},
{id: 4, name: "Bob" ,sex: "M"},
{id: 5, name: "Anna" ,sex: "F"}
],
links: [
{source: 0, target: 1},
{source: 0, target: 3},
{source: 0, target: 4},
{source: 1, target: 2},
{source: 1, target: 5},
{source: 2, target: 5},
{source: 3, target: 4},
{source: 4, target: 5}
]
}
var width = 960;
var height = 500;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var force = d3.layout.force()
.nodes(dataset.nodes)
.links(dataset.links)
.charge(-200)
.linkDistance(200)
.size([width, height])
.start();
var link = svg.selectAll(".link")
.data(dataset.links)
.enter()
.append("line")
.attr("class", "link");
var node = svg.selectAll(".node")
.data(dataset.nodes)
.enter()
.append("circle")
.attr("class", "node")
.attr("r", 10)
.style("fill", function(d) {
if(d.sex == "M"){
return "blue";
}else{
return "red";
}
})
.call(force.drag);
node.append("title")
.text(function(d) { return d.name; });
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>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment