d3 Node Labeling

85,678

Solution 1

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).

Solution 2

I found this guide very useful in trying to accomplish something similar :

https://www.dashingd3js.com/svg-text-element

Based on above link this code will generate circle labels :

<!DOCTYPE html>
<html>
  <head>
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
      <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
   </head>
<body style="overflow: hidden;">
<div id="canvas"  style="overflow: hidden;"></div>

<script type="text/javascript">

    var graph = {
        "nodes": [
            {name: "1", "group": 1, x: 100, y: 90, r: 10 , connected : "2"},
            {name: "2", "group": 1, x: 200, y: 50, r: 15, connected : "1"},
            {name: "3", "group": 2, x: 200, y: 130, r: 25, connected : "1"}
        ]
    }

    $( document ).ready(function() {

        var width = 2000;
        var height = 2000;

        var svg = d3.select("#canvas").append("svg")
                .attr("width", width)
                .attr("height", height)
                .append("g");

        var lines = svg.attr("class", "line")
                .selectAll("line").data(graph.nodes)
                .enter().append("line")
                .style("stroke", "gray") // <<<<< Add a color
                .attr("x1", function (d, i) {
                    return d.x
                })
                .attr("y1", function (d) {
                    return d.y
                })
                .attr("x2", function (d) {
                    return findAttribute(d.connected).x
                })
                .attr("y2", function (d) {
                    return findAttribute(d.connected).y
                })

        var circles = svg.selectAll("circle")
                .data(graph.nodes)
                .enter().append("circle")
                .style("stroke", "gray")
                .style("fill", "white")
                .attr("r", function (d, i) {
                    return d.r
                })
                .attr("cx", function (d, i) {
                    return d.x
                })
                .attr("cy", function (d, i) {
                    return d.y
                });

        var text = svg.selectAll("text")
                                .data(graph.nodes)
                                .enter()
                               .append("text");

        var textLabels = text
          .attr("x", function(d) { return d.x; })
          .attr("y", function(d) { return d.y; })
          .text( function (d) { return d.name })
          .attr("font-family", "sans-serif")
          .attr("font-size", "10px")
          .attr("fill", "red");

    });

    function findAttribute(name) {
        for (var i = 0, len = graph.nodes.length; i < len; i++) {
            if (graph.nodes[i].name === name)
                return graph.nodes[i]; // Return as soon as the object is found
        }
        return null; // The object was not found
    }


</script>
</body>
</html>

Solution 3

If you want to grow the nodes to fit large labels, you can use the getBBox property of an SVG text node after you've drawn it. Here's how I did it, for a list of nodes with fixed coordinates, and two possible shapes:

nodes.forEach(function(v) {
  var nd;
  var cx = v.coord[0];
  var cy = v.coord[1];

  switch (v.shape) {
    case "circle":
      nd = svg.append("circle");
      break;
    case "rectangle":
      nd = svg.append("rect");
      break;
  }

  var w = 10;
  var h = 10;
  if (v.label != "") {
    var lText = svg.append("text");

    lText.attr("x", cx)
         .attr("y", cy + 5)
         .attr("class", "labelText")
         .text(v.label);

    var bbox = lText.node().getBBox();
    w = Math.max(w,bbox.width);
    h = Math.max(h,bbox.height);
  }

  var pad = 4;

  switch (v.shape) {
    case "circle":
      nd.attr("cx", cx)
        .attr("cy", cy)
        .attr("r", Math.sqrt(w*w + h*h)/2 + pad);
      break;
    case "rectangle":
      nd.attr("x", cx - w/2 - pad)
        .attr("y", cy - h/2 - pad)
        .attr("width", w + 2*pad)
        .attr("height", h + 2*pad);
      break;
  }

});

Note that the shape is added, the text is added, then the shape is positioned, in order to get the text to show on top.

Share:
85,678
Josh Bradley
Author by

Josh Bradley

I am a Computer Science graduate student at the University of Maryland. There's never enough time in the day, but I try to keep up to pace with everything that's going on in both the CS and Math world. I've been programming for years now and I love to learn new languages. I've had experience with most of the "big contenders" out there including Python, Java, C, and C++. Even though I probably ask way too many questions on stack overflow, I hope to one day to give back to the community more than I've taken (knowledge).

Updated on August 22, 2020

Comments

  • Josh Bradley
    Josh Bradley over 3 years

    I've been using the sample code from this d3 project to learn how to display d3 graphs and I can't seem to get text to show up in the middle of the circles (similar to this example and this example). I've looked at other examples and have tried adding

    node.append("title").text("Node Name To Display")
    

    and

    node.append("text")
        .attr("text-anchor", "middle")
        .attr("dy", ".3em").text("Node Name To Display")
    

    right after node is defined but the only results I see is "Node Name To Display" is showing up when I hover over each node. It's not showing up as text inside the circle. Do I have to write my own svg text object and determine the coordinates of that it needs to be placed at based on the coordinates of radius of the circle? From the other two examples, it would seem like d3 already takes cares of this somehow. I just don't know the right attribute to call/set.