block by sathomas 1ca23ee9588580d768aa

Understanding D3.js Force Layout - 5: charge

Full Screen

This is part of a series of examples that describe the basic operation of the D3.js force layout. Eventually they may end up in a blog post that wraps everything together. If you missed the beginning of the series, here’s a link to first example.

The previous example shows how linkDistance tells the force layout the desired distance between connected nodes. It may seem strange that D3 doesn’t simply compel all links to be that distance. The force layout, however, takes other factors into account as well, which sometimes prevents it from achieving the exact link distance in all cases.

One of these additional factors is charge, so named because it’s a property that acts like electrical charge on the nodes. With force-directed graphs in particular, charge causes nodes in the graph to repel each other. This behavior is generally desirable because it tends to prevent the nodes from overlapping each other in the visualization.

The two graphs in the visualization are the same except for their charge. The nodes in the left-most graph have a weaker charge than those on the right. In general, the effect of charge decays rapidly as nodes move farther apart. As the code for this example indicates, it takes a large difference in charge values (in this case, an order of magnitude) to make the two graphs distinct.

Step through the graph one iteration at a time, watch it in slow motion, or play it at full speed using the buttons in the upper left.

The next example looks at a more important use of charge.

index.html