Problems adding and removing nodes in a force-layout using d3.js

点点圈 提交于 2019-12-01 12:26:25
paxRoman

What you mention in there is the default behaviour of D3. When you add nodes they will be inserted in the upper left corner. You can change this behaviour by writing your own placement method and directly setting the X and Y of each node when you add it to your force directed graph.

The trick is to apply this algorithm:

1) calculate the limits of the viewport (say the limits of your drawing area - 20) and use the tricks from the force directed bound example ( http://bl.ocks.org/1129492 )

2) then for each visualization tick do this: calculate forces to keep nodes in viewport

3) the algorithm to keep node in viewport would be something along these lines: for each node calculate X and Y according to the forces that can be applied on the 4 directions (top left, bottom left, top right, bottom right) - if it's closer to upper left then you will set X and Y accordingly....anyway it will not be outside the screen....

Another trick would be to set up the root node in the center (see this post: How do I set the focal node in a D3.js Force Directed Graph?). That would help stabilize your graph. Another advice would be to try to not mix ajax calls with your redraws. Ideally use some callbacks and call redraw when data is loaded, otherwise you will end up with spaghetti code (it's not unusual for force directed graphs to be larger than 1000 lines).

Hope it helps.

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