2014-11-24 6 views
0

예를 들어 here에 이어 d3을 사용하여 강제 지시 그래프를 만들었습니다. 여기에 지금까지이 작업은 다음과 같습니다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을 선택하고 올바른 텍스트 레이블을 포함하는 노드 (SVG 원)에 <text>를 추가합니다. 예를 들어, 내 CSS는 다음과 같습니다.

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

그러나 텍스트 레이블은 표시되지 않습니다. 여기서 내가 뭘 잘못하고 있니?

답변

1

아래의 답변을 위해 귀하의 데이터가 귀하의 예가 아니라고 가정하고 귀하는 label 속성 (예에서는 이름)을 가지고 있습니다.

즉, 잘못된 SVG가 생성됩니다. 당신은 text의 자녀와 circle를 가질 수 없습니다, 당신은 g A의를 포장해야합니다

// 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.

관련 문제