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

前端 未结 1 1292
有刺的猬
有刺的猬 2021-01-16 02:16

I am trying to visualize the server availability (and later other things, once this works) by fetching data from the Zabbix API. You can see an example on how the data retur

相关标签:
1条回答
  • 2021-01-16 02:56

    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.

    0 讨论(0)
提交回复
热议问题