How to add compound node in a D3 force layout?

shinjin picture shinjin · Feb 9, 2012 · Viewed 9.3k times · Source

I'm adding nodes to a force layout graph like this:

var node = vis.selectAll("circle.node")
    .data(nodes)
    .enter()
    .append("circle")
    .attr("class", "node")
    .attr("cx", function(d) { return d.x; })
    .attr("cy", function(d) { return d.y; })
    .attr("r", 5)
    .style("fill", function(d) { return fill(d.group); })
    .call(force.drag);

Is there a way to add compound SVG elements as nodes? I.e. I want to add a hyperlink for each circle, so I'd need something like this:

<a href="whatever.com"><circle ...></circle></a>

Answer

Jason Davies picture Jason Davies · Feb 11, 2012

Creating a "compound" element is as simple as appending one or more children to another element. In your example, you want to bind your data to a selection of <a> elements, and give each <a> a single <circle> child.

First of all, you need to select "a.node" instead of "circle.node". This is because your hyperlinks are going to be the parent elements. If there isn't an obvious parent element, and you just want to add multiple elements for each datum, use <g>, SVG's group element.

Then, you want to append one <a> element to each node in the entering selection. This creates your hyperlinks. After setting each hyperlink's attributes, you want to give it a <circle> child. Simple: just call .append("circle").

var node = vis.selectAll("a.node")
    .data(nodes);

// The entering selection: create the new <a> elements here.
// These elements are automatically part of the update selection in "node".
var nodeEnter = node.enter().append("a")
    .attr("class", "node")
    .attr("xlink:href", "http://whatever.com")
    .call(force.drag);

// Appends a new <circle> element to each element in nodeEnter.
nodeEnter.append("circle")
    .attr("r", 5)
    .style("fill", function(d) { return fill(d.group); })

node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });

Remember that D3 primarily operates on selections of nodes. So calling .append() on the entering selection means that each node in the selection gets a new child. Powerful stuff!

One more thing: SVG has its own <a> element, which is what I was referring to above. This is different from the HTML one! Typically, you only use SVG elements with SVG, and HTML with HTML.

Thanks to @mbostock for suggesting that I clarify the variable naming.