简体   繁体   中英

How can I get d3 to display my text labels?

I'm making a force-directed graph using d3, following the example here . Here's what I have so far:

var width = 600,
  height = 600;

var svg = d3.select('#d3container')
  .append('svg')
  .attr('width', width)
  .attr('height', height);

// draw the graph nodes
var node = svg.selectAll("circle.node")
  .data(mydata.nodes)
  .enter()
  .append("circle")
  .attr("class", "node")
  .style("fill", "red")
  .attr("r", 12);

node.append("text")
  .attr("dx", 9)
  .attr("dy", ".35em")
  .text(function(d) {
    return d.label
  });

// draw the graph edges
var link = svg.selectAll("line.link")
  .data(mydata.links)
  .enter().append("line")
  .style('stroke', 'black')
  .style("stroke-width", function(d) {
    return (d.strength / 75);
  });

// create the layout
var force = d3.layout.force()
  .charge(-220)
  .linkDistance(90)
  .size([width, height])
  .nodes(mydata.nodes)
  .links(mydata.links)
  .start();

// define what to do one each tick of the animation
force.on("tick", function() {
  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;
    });

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

// bind the drag interaction to the nodes
node.call(force.drag);

This correctly selects my d.label and appends <text> to the nodes (svg circles) containing the correct text labels. Following the example, my CSS is:

.node text { 
    pointer-events: none; 
    font: 10px sans-serif; 
} 

Yet the text labels don't display. What am I doing wrong here?

Note, for the below answer, I'm assuming your data is different then your example and you have a label property (it's name in the example).

That stated, you are producing invalid SVG. You can't have a circle with a child of text , you need to wrap them in a g :

// draw the graph nodes
var node = svg.selectAll("circle.node")
  .data(mydata.nodes)
  .enter()
  .append("g");

node.append("circle")
  .attr("class", "node")
  .style("fill", "red")
  .attr("r", 12);

node.append("text")
  .attr("dx", 9)
  .attr("dy", ".35em")
  .text(function(d) {
    return d.label;
  });

Example here .

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