Multiple instances of d3 force layout on the same page

前端 未结 2 533
攒了一身酷
攒了一身酷 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.

    0 讨论(0)
  • 2021-01-12 20:27

    Javascript is notorious for obfuscating whether state is shared or not. Your minimal example is no longer available, but when I encountered the same problem, my conclusion was that I was only making shallow copies where I needed complete clones. (I'm talking about the links and nodes that D3 takes as input.)

    Without a true copy, the resulting behavior will be a bit random, as you discovered, depending on whether D3 code choses to modify any shared data "in situ" or not. In general, D3 tries not to create copies, for performance reasons.

    This is why the json call workaround works: by completely stringifying all the data, you are de facto forcing a clone operation.

    0 讨论(0)
提交回复
热议问题