2014-11-24 3 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. Вы не можете иметь circle с ребенком text, вам нужно обернуть их в 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.

Смежные вопросы