2016-06-05 22 views
5

To jest mój kod wyglądający, możesz również mieć pełny kod na JsFiddle. Chcę mieć etykiety na każdym węźle, ale nie mogę. Nawiasem mówiąc, etykiety mogą być osadzone w kole w console.Dodaj etykietę tekstową do węzła d3 w układzie Force

var nodes = svg.selectAll("circle") 
        .data(dataset.nodes) 
        .enter() 
        .append("circle") 
        .attr("r", 10) 
        .style("fill", function(d, i){ 
         return colors(i); 
        }) 
        .call(force.drag); 
    var label = nodes.append("svg:text") 
        .text(function (d) { return d.name; }) 
        .style("text-anchor", "middle") 
        .style("fill", "#555") 
        .style("font-family", "Arial") 
        .style("font-size", 12); 



    force.on("tick", function(){ 
     edges.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; }); 
     nodes.attr("cx", function(d){ return d.x; }) 
      .attr("cy", function(d){ return d.y; }); 
     label.attr("x", function(d){ return d.x; }) 
      .attr("y", function (d) {return d.y - 10; }); 


    }); 

Odpowiedz

8

Oto skrzypce: https://jsfiddle.net/gerardofurtado/7pvhxfzg/1/

Teraz jesteś dołączanie text elementy do circle elementów. Kiedy piszesz:

var label = nodes.append("svg:text") 

Trzeba pamiętać, co nodes jest:

var nodes = svg.selectAll("circle") 
        .data(dataset.nodes) 
        .enter() 
        .append("circle") 

Zatem jesteś dołączanie tekstów do kręgów, i że nie działa. Pojawiają się na konsoli (jako <circle><text></text></circle>), ale nic nie pojawi się w SVG.

Wystarczy zmienić na:

var label = svg.selectAll(".mytext") 
        .data(dataset.nodes) 
        .enter() 
        .append("text") 
        .text(function (d) { return d.name; }) 
        .style("text-anchor", "middle") 
        .style("fill", "#555") 
        .style("font-family", "Arial") 
        .style("font-size", 12); 
+1

dzięki. To działa!!! :) –

Powiązane problemy