0
votes

Apologies as this is no doubt a stupid question but i've been playing around for hours now and cannot get this to work.

I have my force directed graph working nicely, with groups, and i'm trying to add labels to the nodes.

However, I just cannot get it to work! I won't paste code from my many failed attempts, instead this is what i use to draw the graph now; how would I go about adding d.id as a text label to the node??

  let g = svg
      .append("g")
      .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"),
    link = g
      .append("g")
      .attr("stroke", "#000")
      .attr("stroke-width", 1.5)
      .selectAll(".link"),
    node = g
      .append("g")
      .attr("stroke", "#fff")
      .attr("stroke-width", 1.5)
      .selectAll(".node");

    // Apply the general update pattern to the nodes.
    node = node.data(nodes, function(d) {
      return d.id;
    });
    node.exit().remove();
    node = node
      .enter()
      .append("circle")
      .attr("fill", function(d) {
        return color(d.group);
      })
      .attr("r", 15)
      .merge(node);

enter image description here

1
"I won't paste code from my many failed attempts"... it's impossible to help you if you don't do. - Gerardo Furtado

1 Answers

-1
votes

let allNodes = svg.selectAll(".node").data(nodes, d => d.id)

let newNodes = allNodes.enter().append("g").classed("node", true);

...

newNodes.append("circle").attr("fill", ...).attr("r", 15)

newNodes.append("text").text(d => d.id)

...

allNodes = newNodes.merge(allNodes)

allNodes.exit().remove()