Multiple instances of d3 force layout on the same page

前端 未结 2 416
攒了一身酷
攒了一身酷 2021-01-12 19:44

My goal is to use the d3 force layout to display two different networks that share the same nodes. For example, among four people, you could define a social network and a ge

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-12 20:20

    I wrote a tool that allows browsing biological regulatory networks, showing two SVG panels side-by-side. Each panel contains a force-layout network, as drawn by the d3.js API.

    I found that the key to making this work is to give every element in the DOM a unique name, where there can be duplication.

    In my case, I used _left and _right as suffices to every panel element, where the element is in the left or right panel, respectively. It is a lot of work to keep track of, but the network renderer can target its calls and events to the correct element and network.

    In your case:

    .attr("id", function(d,i) {
          return ("idx" + i);
          })
    

    You want to replace the return value with something that uniquely addresses the network that the node is associated with. Whether you use a index numbering scheme or a suffix-based approach, like I did, the trick is to make sure all id names are unique.

提交回复
热议问题