0

I need to add text labels to this D3 force directed chart (from Zoomable Force Directed Graph d3v4 link). However I dont understand the edits that are required to add labels to both the circle and to the link. The node label is attribute "node.label", and the edge label is attribute "edge.label". This d3 Node Labeling explains the edit needed but I've not been able to get it to work (I'm not a JS programmer unfortunately). How can I edit this so that attribute "node.label" can be added for the node, and attribute "edge.label" to the edge?

//add encompassing group for the zoom
var g = svg.append("g")
    .attr("class", "everything");

//draw lines for the links
var link = g.append("g")
    .attr("class", "links")
    .selectAll("line")
    .data(links_data)
    .enter().append("line")
    .attr("stroke-width", 2)
    .style("stroke", linkColour);

//draw circles for the nodes
var node = g.append("g")
        .attr("class", "nodes")
        .selectAll("circle")
        .data(nodes_data)
        .enter()
        .append("circle")
        .attr("r", radius)
        .attr("fill", circleColour);
MarkTeehan
  • 303
  • 7
  • 18

1 Answers1

0

what you can do is it to make your node a < g > instead a circle, add a text to it. Also you have to change the tickActions function so it move < g > :

drawing node as g :

var node = g.append("g")
        .attr("class", "nodes")
        .selectAll(".node")
        .data(nodes_data)
        .enter()
        .append("g")
        .attr("class","node")
        .each(function(d){
            d3.select(this)
                    .append("circle")
                    .attr("r", radius)
                    .attr("fill", circleColour(d));
            d3.select(this)
                    .append("text").text(d.name)
                    .attr("dy",radius+10)
                    .style("text-anchor","middle");
        });

tick function :

function tickActions() {
    //update node positions each tick of the simulation
    node
            .attr("transform", function(d) { return "translate("+d.x+","+ d.y+")"; });

    //update link positions
    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; });
}
Lary Ciminera
  • 1,270
  • 8
  • 15