Home > Mobile >  D3js force directed graph change strength of connections
D3js force directed graph change strength of connections

Time:06-14

I am using D3js to create a force directed graph.

How can I change the strength of the connections? In my case, I want to reduce the strength of the connections so that the nodes are further apart in general and the overall graph gets a lot looser and more usable. (See image at the end for current result). Changing the value attribute only changed the displayed thickness of the connections, not their "physical" strength.

JSON data (over 12000 lines, so I don't want to put it in this post directly): Current result

CodePudding user response:

For any change in property in d3 forceSimulation, you can refer this api https://github.com/d3/d3-force and change the below initialization of the force simulation.

var simulation = d3.forceSimulation()
  .force("link", d3.forceLink().id(function(d) {
    return d.id;
  }))
  .force("charge", d3.forceManyBody())
  .force("center", d3.forceCenter(width / 2, height / 2));

For what I understood you want to increase the distance between links. for that you can use distance property and add it in your initialization of the simulation, something like below. You can try various properties of link, node, center and charge by refering the above api. Add .distance([200]) to your links and see is that what you want.

var simulation = d3.forceSimulation()
  .force("link", d3.forceLink().id(function(d) {
    return d.id;
  }).distance([200]))
  .force("charge", d3.forceManyBody())
  .force("center", d3.forceCenter(width / 2, height / 2));

Also if you want no overlapping nodes, add collide property to your force simulation, change the strength between 0 and 1. You will have to read through various properties in the api and add them in initialization till you find desired result

var simulation = d3.forceSimulation()
  .force("link", d3.forceLink().id(function(d) {
    return d.id;
  }).distance([100]))
  .force("charge", d3.forceManyBody())
  .force("center", d3.forceCenter(width / 2, height / 2))
  .force("collide", d3.forceCollide().strength([0.3]));
  • Related