2014-02-07 40 views
0

我是d3.js的新手,我對語法感到困惑。將標籤添加到/更新爲d3.js圖

我平時知道如何標籤添加到圖......而與此代碼(我從D3.js Force Layout - showing only part of a graph採取)

我曾嘗試各種解決方案[.append(「文本」),進入().append(「text」)....]但我一直沒有成功。

這裏就是我認爲我必須要改變一些代碼的一部分(和,下面的代碼,你會發現整個事情gihub回購)

 this.link = this.link.data(this.force.links(), function (d) { 

      return d.source.id + "-" + d.target.id; 
     }); 

     this.link.enter().insert("line", ".node").attr("class", "link") 

      .style("opacity", 0) 
      .transition().duration(1000) 

      .style("opacity", 1); 

     this.link.exit() 
      .remove(); 



     this.node = this.node.data(this.force.nodes(), function (d) { 
      return d.id; 

     }); 

     if (this.node.enter().empty()==false ||this.node.exit().empty() == false) { 
      transition = true; 
     } 


     this.node.enter() 
      .append("circle") 
      .style("opacity", 1) 
      .attr("class", "node") 
      .style("fill", function (d) { 
       return d.color; 
      }) 
      .attr("r", 18) 
      /*.on('mouseover', this.mouseOver)*/ 
      .on('mousedown', this.mouseDown) 
      .on('mouseout', this.mouseOut) 
      .on("dragstart", this.dragStart) 
      .on("click", this.click) 
      .call(this.nodeDrag) 
      .transition().duration(1000) 
      .style("opacity", 1) 
      .each("end",function(){transition=false;}); 


     this.node.each(function(d) { 
      if (d.centerNode==false) { 
       this.setAttribute('r',12); 
      } else if (firstRound) { 
       this.setAttribute('r',30); 
       firstRound =false; 
      } 
     }); 





     this.node.exit().transition().duration(1000).style("opacity", 0) 
      .each("end",function(){transition=false;}) 
      .remove(); 

https://github.com/coulmont/pornograph

+1

你想追加標籤到什麼地方? 'node'? –

+0

是的!我想將標籤附加到節點(無論是在節點的中心還是側面) – user1788720

回答

1

要爲一個.enter()選擇附加多組元素,您需要多次訪問它。分組元素通常是一個好主意。

var gs = this.node.enter().append("g"); 
gs.append("circle") 
     .style("opacity", 1) 
     .attr("class", "node") 
     .style("fill", function (d) { 
      return d.color; 
     }) // etc 
gs.append("text") 
    .style("text-anchor", "center") 
    .text(...); 
+0

謝謝...不工作...您認爲我需要將「this.node」的每個實例替換爲「 gs「? – user1788720

+1

是的,您的其他代碼將不得不反映這種變化。簡單地重新分配'this.node'可能會更容易。 –

+0

重新分配意味着這個? var this.node = this.node.enter()。append(「g」); – user1788720