How to update elements of D3 force layout when the underlying data changes

后端 未结 2 1200
慢半拍i
慢半拍i 2020-12-29 05:15

I\'m using one of the force layout examples (http://bl.ocks.org/1153292) to show a network on my web site.

I allow the user to choose which type of links to see at a

2条回答
  •  盖世英雄少女心
    2020-12-29 06:13

    There is an example at http://bl.ocks.org/1095795 that shows adding and removing nodes from a force directed layout. The links and nodes have to be handled separately and then the force layout has to be restarted.

    function restart() {
      var link = vis.selectAll("line.link")
          .data(links, function(d) { return d.source.id + "-" + d.target.id; });
    
      link.enter().insert("svg:line", "g.node")
          .attr("class", "link");
    
      link.exit().remove();
    
      var node = vis.selectAll("g.node")
          .data(nodes, function(d) { return d.id;});
    
      var nodeEnter = node.enter().append("svg:g")
          .attr("class", "node")
          .call(force.drag);
    
      nodeEnter.append("svg:image")
          .attr("class", "circle")
          .attr("xlink:href", "https://d3nwyuy0nl342s.cloudfront.net/images/icons/public.png")
          .attr("x", "-8px")
          .attr("y", "-8px")
          .attr("width", "16px")
          .attr("height", "16px");
    
      nodeEnter.append("svg:text")
          .attr("class", "nodetext")
          .attr("dx", 12)
          .attr("dy", ".35em")
          .text(function(d) { return d.id });
    
      node.exit().remove();
    
      force.start();
    }
    

提交回复
热议问题