Skip to content

Instantly share code, notes, and snippets.

@katsumitakano
Created March 20, 2014 13:01
Show Gist options
  • Save katsumitakano/9663256 to your computer and use it in GitHub Desktop.
Save katsumitakano/9663256 to your computer and use it in GitHub Desktop.
Force Layout 【Text】
<!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 {
font-size: 25px;
}
.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("text")
.attr("class", "node")
.attr("dx", "-20")
.style("fill", function(d) {
if(d.sex == "M"){
return "blue";
}else{
return "red";
}
})
.text(function(d){ return d.name; })
.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("x", function(d) { return d.x; })
.attr("y", 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