Friday, 1 March 2019

How can I center the text in a node?

I'm learning about d3.js and the system of forces. I have a blocker because I am not able to add a text and it is perfectly centered within the circle. I had tried to create <text> but it does not work. How can I achieve it?

In this piece I tried to create a text element but it does not work.

    var node = g.append("g")
        .attr("class", "nodes")
        .selectAll("circle")
        .data(graph.nodes)
        .enter()
        .append("circle")
        .attr("r", 20)
        .attr("fill", function(d){
          return colorNode(d.group);
        })
        .style("stroke", function(d){
          return colorNode(d.group);
        })

enter image description here

UPDATE I know that I must somehow make that within a g element, this content the circle and a text, but I can not make it work. obviously, I also do not know how to center the text inside the circle. My result is that the circle appears outside the force diagram. I have tried this, but not works:

    var node = g.append("g")
        .attr("class", "nodes")
        .selectAll("g")
        .data(graph.nodes)
        .enter()
        .append("g");
        node.append("circle")
        .attr("r", 20)
        .attr("fill", function(d){
          return colorNode(d.group);
        })
        .style("stroke", function(d){
          return colorNode(d.group);
        })

this is my full code:

https://plnkr.co/edit/JhjhFKQgKVtmYQXmgbzF?p=preview



from How can I center the text in a node?

No comments:

Post a Comment