0

I want to make an SVG group to store a node and text in it. My generated HTML looks like this:

<g class="node" cx="946.6911642155153" cy="434.4579018064595">
    <circle class="circle" r="4.5" />
    <text dx="12" dy="0.35em">Harry Potter</text>
</g>

Nevertheless, the nodes and the text are stuck in the top left corner. I tried to build it from this question on SO.

My code looks like this:

function draw() {    
    node = svg.selectAll(".node");
    node = node.data(force.nodes(), function(d) { return d.id;});
    var gnode = node.enter().append('g').attr("class", "node");
    gnode.append("circle").attr("class", "circle").attr("r", 4.5);

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

    force.start();
}

A working demo can be found here. I suspect that I have to push the gnode to the force.nodes(), but I am not a 100% sure.

Community
  • 1
  • 1
Peter
  • 1,844
  • 2
  • 31
  • 55

1 Answers1

1

Your SVG is not correct since the attributes cx and cy are not valid for g elements. They are only applicable to circle elements.

To place the group elements you may use a transformation to translate the g. A simple change in your tick function will solve this:

function tick() {
    node.attr("transform", function(d) {
        return "translate(" + d.x + " " + d.y + ")";
    });
//    node.attr("cx", function(d) { return d.x; })
//        .attr("cy", function(d) { return d.y; });

    link.attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });
}
altocumulus
  • 21,179
  • 13
  • 61
  • 84