2017-07-29 82 views
0

我使用了這裏的網絡圖例如: https://bl.ocks.org/mbostock/4062045如何添加文本到力向圖中D3.js

我想添加文本元素到節點,但似乎無法得到它出現在節點旁邊。

我試着在下面的函數中添加下面幾行,但是這樣做是爲了在屏幕左上角顯示文本 - 我期望它出現在左上角。

不確定是否有人可以幫忙?

var textElements = svg.append("g") 
.selectAll('text') 
    .data(graph.nodes) 
    .enter().append('text').attr('font-size', 15) 
.attr('dx', 15) 
.attr('dy', 4) 
    .text(function(d) { return d.id; }); 

原文:

d3.json("miserables.json", function(error, graph) { 
    if (error) throw error; 

    var link = svg.append("g") 
    .attr("class", "links") 
    .selectAll("line") 
    .data(graph.links) 
    .enter().append("line") 
    .attr("stroke-width", function(d) { return Math.sqrt(d.value); }); 



    var node = svg.append("g") 
    .attr("class", "nodes") 
    .selectAll("circle") 
    .data(graph.nodes) 
    .enter().append("circle") 
    .attr("r", 5) 
    .attr("fill", function(d) { return color(d.group); }) 
    .call(d3.drag() 
      .on("start", dragstarted) 
      .on("drag", dragged) 
      .on("end", dragended)); 

    node.append("title") 
    .text(function(d) { return d.id; }); 


    simulation 
    .nodes(graph.nodes) 
    .on("tick", ticked); 

    simulation.force("link") 
    .links(graph.links); 



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

回答