d3 Node Labeling

There are lots of examples showing how to add labels to graph and tree visualizations, but I’d probably start with this one as the simplest:

You haven’t posted a link to your code, but I’m guessing that node refers to a selection of SVG circle elements. You can’t add text elements to circle elements because circle elements are not containers; adding a text element to a circle will be ignored.

Typically you use a G element to group a circle element (or an image element, as above) and a text element for each node. The resulting structure looks like this:

<g class="node" transform="translate(130,492)">
  <circle r="4.5"/>
  <text dx="12" dy=".35em">Gavroche</text>
</g>

Use a data-join to create the G elements for each node, and then use selection.append to add a circle and a text element for each. Something like this:

var node = svg.selectAll(".node")
    .data(nodes)
  .enter().append("g")
    .attr("class", "node")
    .call(force.drag);

node.append("circle")
    .attr("r", 4.5);

node.append("text")
    .attr("dx", 12)
    .attr("dy", ".35em")
    .text(function(d) { return d.name });

One downside of this approach is that you may want the labels to be drawn on top of the circles. Since SVG does not yet support z-index, elements are drawn in document order; so, the above approach causes a label to be drawn above its circle, but it may be drawn under other circles. You can fix this by using two data-joins and creating separate groups for circles and labels, like so:

<g class="nodes">
  <circle transform="translate(130,492)" r="4.5"/>
  <circle transform="translate(110,249)" r="4.5"/>
  …
</g>
<g class="labels">
  <text transform="translate(130,492)" dx="12" dy=".35em">Gavroche</text>
  <text transform="translate(110,249)" dx="12" dy=".35em">Valjean</text>
  …
</g>

And the corresponding JavaScript:

var circle = svg.append("g")
    .attr("class", "nodes")
  .selectAll("circle")
    .data(nodes)
  .enter().append("circle")
    .attr("r", 4.5)
    .call(force.drag);

var text = svg.append("g")
    .attr("class", "labels")
  .selectAll("text")
    .data(nodes)
  .enter().append("text")
    .attr("dx", 12)
    .attr("dy", ".35em")
    .text(function(d) { return d.name });

This technique is used in the Mobile Patent Suits example (with an additional text element used to create a white shadow).

Leave a Comment