2014-11-24 33 views
0

我正在使用d3製作一個強制定向圖形,遵循示例here。這是我到目前爲止有:如何讓d3顯示我的文字標籤?

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

這正確地選擇我的d.label並追加<text>包含正確的文本標籤的節點(SVG圓圈)。下面的例子,我的CSS是:

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

但文本標籤不顯示。我在這裏做錯了什麼?

回答

1

請注意,對於下面的答案,我假設您的數據不同於您的示例,並且您有一個label屬性(它是該示例中的名稱)。

這表明,您正在生成無效的SVG。你不能有的text一個孩子circle,你需要用他們在一個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; 
    }); 

here