d3.js force directed layout constrained by a shape

妖精的绣舞 提交于 2019-12-21 01:19:20

问题


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?


回答1:


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:

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



来源:https://stackoverflow.com/questions/15100060/d3-js-force-directed-layout-constrained-by-a-shape

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!