简体   繁体   中英

How to add node labels to Bounded Force Layout (D3 v4)?

Latest code attempt:

 var node = svg.selectAll("circle")
      .data(graph.nodes)
    .enter().append("circle")
      .attr("r", radius - .75)
      .style("fill", function(d) { return fill(d.group); })
      .style("stroke", function(d) { return d3.rgb(fill(d.group)).darker(); })
      .call(force.drag);

  var label = svg.selectAll("text")
    .data(graph.nodes)
    .enter()
    .append("text")
    .text(function(d){return d.id; }); 
    .style("text-anchor", "middle")
    .attr("font-family", "sans-serif")
    .attr("font-size", "11px")
    .attr("fill", "red");
 })

  force
      .nodes(graph.nodes)
      .links(graph.links)
      .on("tick", tick)
      .start();

  function tick() {
    node.attr("cx", function(d) { return d.x = Math.max(radius, Math.min(width - radius, d.x)); })
        .attr("cy", function(d) { return d.y = Math.max(radius, Math.min(height - radius, 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; });

    label.attr("x", function(d){ return d.x; })
          .attr("y", function (d) {return d.y });

Hi Everyone,

I am a newbie to D3 and have spent almost two days on this problem so far to no avail!

I am trying to add node labels to a version of https://bl.ocks.org/mbostock/1129492

I've copy/pasted snippets of code from every forum response I can find and it either breaks my diagram (empty screen on execution) or has no effect (lots of pretty colored circles but no labels). I have been able to add labels to another force diagram successfully but that one was not bounded, and bounding is a key feature I'd like to have. At this stage I have not made any changes to the graph.json file Bostock put up. I am simply trying to get it to display the node text labels.

Can someone please tell me what code I need to write to get labels to show, and where and how to to insert it? I'm determined to not give up on this one!

Here's my code:

 <!DOCTYPE html> <meta charset="utf-8"> <style> circle { stroke-width: 1.5px; } line { stroke: #999; } text { font: 12px "open sans"; fill: #fff; } </style> <body> <script src="https://d3js.org/d3.v4.min.js"></script> <script> var width = 960, height = 500, radius = 6; var fill = d3.scaleOrdinal() .range(["#a02a65","#2aa02a","#2aa0a0","#a0652a","#a02a2a","#2a2aa0","#65a02a","#a0a02a"]) var simulation = d3.forceSimulation() .velocityDecay(0.1) .force("x", d3.forceX(width / 2).strength(.05)) .force("y", d3.forceY(height / 2).strength(.05)) .force("charge", d3.forceManyBody().strength(-240)) .force("link", d3.forceLink().distance(50).strength(1)); var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height); d3.json("https://[URL HERE]/graph.json", function(error, graph) { if (error) throw error; var link = svg.selectAll("line") .data(graph.links) .enter().append("line"); var node = svg.selectAll("circle") .data(graph.nodes) .enter().append("circle") .attr("r", radius - .75) .style("fill", function(d) { return fill(d.group); }) .style("stroke", function(d) { return d3.rgb(fill(d.group)).darker(); }) .call(d3.drag() .on("start", dragstarted) .on("drag", dragged) .on("end", dragended)); var labels = node.append("text") .text(function(d) { return d.id; }) .attr('x', 6) .attr('y', 3); node.append("title") .text(function(d) { return d.id; });simulation .nodes(graph.nodes) .on("tick", tick); simulation.force('link') .links(graph.links); function tick() { node.attr("cx", function(d) { return dx = Math.max(radius, Math.min(width - radius, dx)); }) .attr("cy", function(d) { return dy = Math.max(radius, Math.min(height - radius, dy)); }); 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; }); } }); function dragstarted(d) { if (!d3.event.active) simulation.alphaTarget(0.3).restart(); d.fx = dx; d.fy = dy; } function dragged(d) { d.fx = d3.event.x; d.fy = d3.event.y; } function dragended(d) { if (!d3.event.active) simulation.alphaTarget(0); d.fx = null; d.fy = null; } </script> 

I have modified the example from Mike Bostock to include labels for each node by doing the following:

  1. The label for each node is in graph.nodes so first we create a selection labels and perform a typical d3 data-join to add text elements and set the label-text.

  2. The positioning of the labels occurs in the tick() function. On each step of the animation, we set the x and y attribute of the text element according to the x and y value of the graph.node element.

Please note that this example uses d3 v3 so there will be some changes to the syntax - primarily the names used for scale etc. More details can be found here .

I have not attempted to position the text to avoid overlapping. This is reasonably involved and discussed elsewhere like this other SO post .

 var width = 960, height = 500, radius = 6; var fill = d3.scale.category20(); var force = d3.layout.force() .gravity(.05) .charge(-240) .linkDistance(50) .size([width, height]); var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height); d3.json("https://gist.githubusercontent.com/mbostock/1129492/raw/9513c3fe193673a09e161d49d00a587fd806bdf5/graph.json", function(error, graph) { if (error) throw error; var link = svg.selectAll("line") .data(graph.links) .enter().append("line"); var node = svg.selectAll("circle") .data(graph.nodes) .enter().append("circle") .attr("r", radius - .75) .style("fill", function(d) { return fill(d.group); }) .style("stroke", function(d) { return d3.rgb(fill(d.group)).darker(); }) .call(force.drag); var labels = svg.selectAll("text") .data(graph.nodes) .enter().append('text') .text(function (d){return d.name}); force .nodes(graph.nodes) .links(graph.links) .on("tick", tick) .start(); function tick() { node.attr("cx", function(d) { return dx = Math.max(radius, Math.min(width - radius, dx)); }) .attr("cy", function(d) { return dy = Math.max(radius, Math.min(height - radius, dy)); }); 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; }); labels.attr('x', function(d) { return dx; }) .attr('y', function(d) { return dy; }); } }); 
 circle { stroke-width: 1.5px; } line { stroke: #999; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM