Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  • all the nodes are equivalently distributed within the shape and
  • the distance between the border and the nodes is equally to the distance between the nodes

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?

like image 439
Michael Avatar asked Feb 26 '13 21:02

Michael


1 Answers

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

like image 139
Frank van Wijk Avatar answered Sep 20 '22 04:09

Frank van Wijk