2017-08-01 83 views
0

我现在用的力布局例子here添加标签强制布局,其中的数据是唯一的客户端(D3)

我需要的标签添加到节点。所有的例子我已经看到了使用这样的事情:

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

但是,当有一个被称为本地数据,如功能这个工程:

d3.json("graph.json", function(error, json) { 

但在我的例子中,数据是所有客户端因此不需要d3.json来传递它。如何在此场景中向每个节点添加标签?下面是我使用的代码:

<body> 
<script src="//d3js.org/d3.v3.min.js"></script> 
<script> 

// set a width and height for our SVG 
var width = 1000, 
height = 800; 

// setup links 
var links = [ 
{ source: 'Baratheon', target:'Lannister' }, 
{ source: 'Baratheon', target:'Stark' }, 
{ source: 'Lannister', target:'Stark' }, 
{ source: 'Stark', target:'Bolton' }, 
]; 

// create empty nodes array 
var nodes = {}; 

// compute nodes from links data 
links.forEach(function(link) { 
    link.source = nodes[link.source] || 
     (nodes[link.source] = {name: link.source}); 
    link.target = nodes[link.target] || 
     (nodes[link.target] = {name: link.target}); 
}); 


// add a SVG to the body for our viz 
var svg=d3.select('body').append('svg') 
    .attr('width', width) 
    .attr('height', height); 

// use the force 
var force = d3.layout.force() 
    .size([width, height]) 
    .nodes(d3.values(nodes)) 
    .links(links) 
    .on("tick", tick) 
    .linkDistance(300) 
    .start(); 

// add links 
var link = svg.selectAll('.link') 
    .data(links) 
    .enter().append('line') 
    .attr('class', 'link'); 

// add nodes 
var node = svg.selectAll('.node') 
    .data(force.nodes()) 
    .enter().append('circle') 
    .attr('class', 'node') 
    .attr('r', width * 0.01); 


// what to do 
function tick(e) { 

    node.attr('cx', function(d) { return d.x; }) 
     .attr('cy', function(d) { return d.y; }) 
     .call(force.drag); 

    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; }); 

} 

</script> 

回答

0

你引用的作品,因为每个节点由.data()方法绑定到一个对象标签的例子。这些对象中的每一个都有一个name属性,其中包含该节点的标签。

在你的代码中,你已经有了这个设置!您的节点绑定到force.nodes()对象的数组,其子对象的属性均为name。您只需致电node.text(function(d) { return d.name })即可。

默认情况下,这些标签将不可见。有关如何显示节点标签的想法,请参阅this question

相关问题