I'm pretty new with D3.js, and I've been playing around with force layout. One of the things I tried was placing labels on links.
One way of doing it is by appending svg:text
and manually calculating translate
& rotate
, which works fine with straight lines. But, in case when link is a svg:path
(e.g. arc), this doesn't work as expected. In these cases, svg:textPath
is suggested solution.
In this demo, you can see a simple implementation of adding labels to links through svg:textPath
. The only problem with it is that, in case when source is positioned to the right of target, text is rendered in opposite direction (from our point of view, it's still correct from path's perspective). My question is, how to deal with this?
The only "solution" I came up with is, manually swapping source and target in case described above. Here, you can see that it almost works.
In state when the swap happens, you can also see arc flipping to other side, which doesn't look right. :(
@LarsKotthoff is correct that the textPath
has to follow the direction of the path. In this case, the direction of the path defines not only the arc direction, but the attachment of the arrow marker on the end - this makes it tricky to swap directions on the fly, as you have to move the marker too.
The simpler solution (though maybe not the best if you have a large number of links) is to "shadow" the real link path with an invisible path used just for text:
var link = svg.append("svg:g").selectAll("g.link")
.data(force.links())
.enter().append('g')
.attr('class', 'link');
var linkPath = link.append("svg:path")
.attr("class", function(d) { return "link " + d.type; })
.attr("marker-end", function(d) { return "url(#" + d.type + ")"; });
var textPath = link.append("svg:path")
.attr("id", function(d) { return d.source.index + "_" + d.target.index; })
.attr("class", "textpath");
Now you have a separate path you can manipulate properly. As you noticed, there are two issues - you have to change the path direction, and you have to change the arc direction. It looks like you can do this in the path command string by swapping the sweep-flag
value (see docs), so instead of Arx,ry 0 0,1
you have Arx,ry 0 0,0
. You can reduce some code duplication by having one function to create path strings:
function arcPath(leftHand, d) {
var start = leftHand ? d.source : d.target,
end = leftHand ? d.target : d.source,
dx = end.x - start.x,
dy = end.y - start.y,
dr = Math.sqrt(dx * dx + dy * dy),
sweep = leftHand ? 0 : 1;
return "M" + start.x + "," + start.y + "A" + dr + "," + dr +
" 0 0," + sweep + " " + end.x + "," + end.y;
}
Then you can update the link path and the text path separately:
linkPath.attr("d", function(d) {
return arcPath(false, d);
});
textPath.attr("d", function(d) {
return arcPath(d.source.x < d.target.x, d);
});
See working code: http://jsfiddle.net/nrabinowitz/VYaGg/2/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With