Skip to content

Commit 7abebef

Browse files
committed
Better center gravity.
Rather than applying gravity to the entire graph, we now apply it to individual nodes, such that disconnected nodes and subgraphs still have a tendency to drift towards the center. In addition, rather than using a standard gravitational force that drops quadratically with distance, we use a weak spring who force increases with distance. This makes the gravitational effect less noticeable near the center, and also makes the effect stronger the more the nodes drift from the center. To balance the center "gravity" with the repulsive charge force, we also normalize the strength of the gravity based on the number of nodes in the graph.
1 parent fd804ce commit 7abebef

4 files changed

Lines changed: 27 additions & 21 deletions

File tree

d3.layout.js

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ d3.layout.force = function() {
159159
drag = .9,
160160
distance = 30,
161161
charge = -60,
162-
gravity = 180,
162+
gravity = .02,
163163
theta = .8,
164164
interval,
165165
nodes,
@@ -248,16 +248,17 @@ d3.layout.force = function() {
248248
accumulate(q);
249249

250250
// apply gravity forces
251-
x = size[0] / 2 - q.cx;
252-
y = size[1] / 2 - q.cy;
253-
l = Math.min(.02, 1 / Math.sqrt(x * x + y * y));
254-
l = alpha * gravity * l * l;
255-
x *= l;
256-
y *= l;
251+
x = size[0] / 2;
252+
y = size[1] / 2;
257253
i = -1; while (++i < n) {
258254
o = nodes[i];
259-
o.fx += x;
260-
o.fy += y;
255+
s = x - o.x;
256+
t = y - o.y;
257+
l = alpha * gravity / n * Math.sqrt(s * s + t * t);
258+
s *= l;
259+
t *= l;
260+
o.fx += s;
261+
o.fy += t;
261262
}
262263

263264
// apply charge forces

0 commit comments

Comments
 (0)