Michael
Michael

Reputation: 1251

d3.js force directed layout constrained by a shape

I was wondering if there is a way to create a force directed layout with d3.js and restrict it by an arbitrary shape in such a way that

I hope there is already such a solution out there. Otherwise my idea is to start with the force directed layout and check the distances from the nodes to the borders in each iteration. Any suggestions from yourside?

Upvotes: 10

Views: 1745

Answers (1)

Frank van Wijk
Frank van Wijk

Reputation: 3262

Your idea is mine too. In the tick function you could add additional forces. This is my suggestion (not tested):

force.on('tick', function(e) {

  node
    .each(calcBorderDistance)
    .attr('transform', function(d) {
      d.x -= e.alpha*(1/Math.pow(d.borderDistance.x,2);
      d.y -= e.alpha*(1/Math.pow(d.borderDistance.y,2);
      return 'translate(' + d.x + ',' + d.y + ')'; // Move node
    });
});

function calcBorderdistance(d) {
  // Insert code here to calculate the distance to the nearest border of your shape
  var x = ..., y = ...;
  d.borderDistance = {'x':x,'y':y};
}

I have the inverse quadratic distance to the nearest border function loosely based on the formulas in excelent paper Drawing Graphs Nicely using Simulated Annealing. Following picture illustrates how methods from this paper affect drawing nodes bounded by a box:

enter image description here

And this picture illustrate case with different constraints, involving links between nodes:

enter image description here

Upvotes: 3

Related Questions