D3力导向图移动文本

时间:2015-11-12 09:41:32

标签: d3.js

我想在D3力导向图中的节点上添加移动标签(例如:http://mbostock.github.io/d3/talk/20111116/force-collapsible.html)。我没有问题添加一些文本(我的data.json中定义的节点名称),但是X / Y位置固定到初始节点X / Y位置。我尝试转换和翻译功能,但没有成功。以下是我的代码示例:

// Update the nodes…
node = vis.selectAll("circle.node")
    .data(nodes, function(d) { return d.id; })
    .style("fill", color);    

node.transition()
    .attr("r", function(d) { return d.children ? 4.5 : Math.sqrt(d.size) / 10; });

// Labels   
node.enter().append("svg:text")     
    .attr("dx", function(d) { return d.x; })
    .attr("dy", function(d) { return d.y; })        
    .attr("fill", "#ffffff")
    .attr('text-anchor', 'center')
    .text(function(d) { return d.name });   

// Enter any new nodes.
node.enter().append("svg:circle")
    .attr("class", "node")    
    .attr("cx", function(d) { return d.x; })
    .attr("cy", function(d) { return d.y; })
    .attr("r", function(d) { return d.children ? 4.5 : Math.sqrt(d.size) / 10; })
    .style("fill", color)
    .on("click", click)  
    .call(force.drag);      

// Exit any old nodes.
node.exit().remove();   
} 

function tick() {
    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; });

}   

1 个答案:

答案 0 :(得分:3)

You will first have to label selection like this

text = vis.selectAll("text.label")    
     .data(nodes);

   // Enter any new label
    text.enter()
        .append("text")
        .attr("class", "label")
        .text(function(d) { return d.name; });
  //remove text for collapsed nodes.
  text.exit().remove();  

Then in the ticks function handle the text move (This is what you were missing as a result of which your text was coming fixed)

function tick() {
  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; });
  //this will handle the label move
  text.attr("transform", function(d){ return "translate("+d.x+","+d.y+")"; });    
}

working example here

Hope this helps!

相关问题