I am looking at samples of D3 force-directed graphs with node labels, and I realised that for the tick function, the function to governing the movement of the node and labels uses a transform-translate method:
node.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
})
instead of the usual without labels.
nodes.attr({"cx":function(d){return d.x;},
"cy":function(d){return d.y;}
});
Would anyone be able to help explain the rationle? Thanks.
When node is a single shape element, we just adjust its positional attributes in the tick function. For eg. if it is a circle, we update its cx and cy attributes.
But when we have multiple elements to be displayed in the same or relative position, we group the elements using <g>
element and apply the positional attribute to the <g>
element. The positional attribute of g
element is transform
. We can create different type of elements (here - circle and text) and adjust their positions independently in the tick function. However, it is better to group elements in such cases.