A force-directed graph using images as nodes, with accompanying text labels.
forked from mbostock's block: Labeled Force Layout
forked from newsummit's block: Labeled Force Layout
xxxxxxxxxx
<meta charset="utf-8">
<style>
.link {
stroke: #ccc;
}
.node text {
pointer-events: none;
font: 10px sans-serif;
}
</style>
<body>
<script src="https://d3js.org/d3.v3.min.js"></script>
<script>
var link,
node,
width = 960,
height = 700,
maxDist = 300,
minDist = 20,
svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height),
force = d3.layout.force()
.gravity(0.05)
.charge(-500)
.size([width, height]);
d3.json("graph.json", function(error, json) {
if (error) throw error;
force
.nodes(json.nodes)
.links(json.links)
.distance(function(d){
//console.log(d.source.index);
return Math.random() * maxDist + minDist;
})
.start();
link = svg.selectAll(".link")
.data(json.links)
.enter().append("line")
.attr("class", "link");
// Create a 'g' node for each data entry
node = svg.selectAll(".node")
.data(json.nodes)
.enter().append("g")
.attr("class", "node");
//.call(force.drag);
// Insert image element
node.append("image")
.attr("xlink:href", "https://github.com/favicon.ico")
.attr("x", -8)
.attr("y", -8)
.attr("width", 16)
.attr("height", 16);
// Insert rect element with no width yet
node.append("rect")
.attr("x", 6)
.attr("y", -10)
.attr("rx", 8)
.attr("ry", 8)
.attr("height", 24)
.style("fill", "#FFE6F0");
// Add title name
node.append("text")
.attr("dx", 12)
.attr("dy", ".35em")
.attr("class", "text")
.attr("data-weight", function(d) { return d.weight; })
.text(function(d) { return d.name });
// Now, set the rect width based on title length
node.selectAll("rect")
.attr("width", function(d) {
var txtWidth = this.parentNode.children[2].getComputedTextLength();
return Math.floor(txtWidth + 15);
});
node.call(force.drag);
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("transform", function(d) {
if (d.index == 0) {
d.x = 500;
d.y = 500;
}
return "translate(" + d.x + "," + d.y + ")";
});
});
});
</script>
https://d3js.org/d3.v3.min.js