9

I cannot display labels of nodes using a force-layout in d3.js.

I'm trying with this example http://d3js.org/d3.v3.min.js

I updated that code only adding zoom, like this:

var svg = d3.select("body").append("svg").attr("width", width).attr("height", height).append('svg:g').call(d3.behavior.zoom().on("zoom", redraw));

function redraw() {
    console.log("here", d3.event.translate, d3.event.scale);
    svg.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")");
    node.attr("transform", function(d) {
        return "translate(" + d.x + "," + d.y + ")";
    });
}

Why are labels not displayed?

VividD
  • 10,456
  • 6
  • 64
  • 111
Giovanni Bitliner
  • 2,032
  • 5
  • 31
  • 50

1 Answers1

4

You need to separately add the text:

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

see these examples:

http://bl.ocks.org/mbostock/2706022

http://bl.ocks.org/mbostock/1153292

philshem
  • 24,761
  • 8
  • 61
  • 127
Marjancek
  • 238
  • 1
  • 3
  • 6
    For the life of me I can't get these labels to appear. I started with the example here http://bl.ocks.org/mbostock/4600693 which already does tooltips but not working. Is there an additional step to tell d3 that the text attribute should be rendered? – Toaster Jan 15 '15 at 13:52
  • Pay attention not to append text element inside circle. If you copy paste from http://bl.ocks.org/mbostock/2706022 (with labels) and https://bl.ocks.org/mbostock/4062045 (no labels) there are little differences. Text **svg** and **circle** svg goes appended to a group **g** element. – user305883 Nov 08 '16 at 23:37