2017-08-05 92 views
0

我有一个基于this block by Mike Bostock更改力布局

首先力布局中使用的数据,我得到我的数据:

var dataNetwork = creationTableaux(seuil); 

哪里creationTableaux是给我我的数据,根据不同的功能节点和链接我要

的号码,然后我创建模拟

 var simulation = d3.forceSimulation() 
      .force("link", d3.forceLink().id(d => d.id)) 
      .force("charge", d3.forceManyBody().strength(-250)) 
      .force("center", d3.forceCenter(width/2, height/2)); 

     var link = canevas2.append("g") 
     .attr("class", "links") 
     .selectAll("line") 
     .data(dataNetwork.links) 
     .enter() 
     .append("line") 
     .attr("stroke", "lightblue") 
     .attr("stroke-width", d => 6 * d.value); 

     var node = canevas2.append("g") 
     .attr("class", "nodes") 
     .selectAll("circle") 
     .data(dataNetwork.nodes) 
     .enter() 
     .append("circle") 
     .attr("r", 5) 
     .attr("fill", "lightblue"); 

     simulation.nodes(dataNetwork.nodes).on("tick", ticked); 

     simulation.force("link").links(dataNetwork.links); 

     function ticked() { 
      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; 
       }); 
     } 

这很好,所以我知道(至少!)这是正确的。现在,所有这一切都包含在另一个函数中,我可以在其中注入不同的csv文件,其中的链接和节点以及未被绘制的文件将被绘制。我用一个按钮调用这个函数,例如当我调用这个函数两次时,这两个图形同时在我的页面上。

我试图遵循一些例子,如this one,但我卡住了。我知道问题来自于所有节点和链接都使用enter()来调用,并且应该有一个exit().remove(),但我应该如何解决这个问题是一个谜。

回答

0

所以我终于找到了一个这样做的方法。在启动模拟之前,我只需删除所有预先存在的元素。

canevas2.selectAll("line").remove(); 
canevas2.selectAll("circle").remove(); 
canevas2.selectAll("text").remove(); 

看不清楚为什么我以前没有想过它!

编辑:当然这种方法的缺点是,“过渡”(如果它可以称为过渡)不会很平滑,因为每次都会重新绘制图表。但它总比没有好:)