Graphics Reference
In-Depth Information
Figure 8-12: Using HTML, you can add a tooltip and explanations to a
circular graph.
D3 Springy Graph
Instead of programming layouts manually, D3 provides some automated
layouts, including a force-directed layout specifically designed for
graphs. Force-directed layouts are sometimes called spring layouts
because the links act like springs pulling nodes together. Chapter 4, “Stats
and Layout,” discusses force-directed layouts in more detail. Spring layouts
are a bit more complex than the layouts previously discussed. Spring layouts
iterate over and over, changing the layout each time to resolve the forces
between all the nodes. You have a number of items to set up in order to use
the springy layout.
First, set up the force-directed graph layout system prior to creating the
SVG scene. In the following code, charge sets repulsion between nodes to
minimize node overlap, linkDistance sets desired link length, and size
sets the overall area available:
var force = d3.layout.force()
.charge(-250)
.linkDistance(100)
.size([width, height]);
Next, the force system is connected to the data. You must provide the force
system with the list of nodes and the list of links. Note that the links do not
refertothenodesbyname, butrather bythenumber implied bytheorderof
thenodesinthefile(withthefirst nodestarting at0).Thisisconsistent with
how you've been using nodes and links up to this point. The final method
( start ) starts the force calculations:
force
.nodes(graph.nodes)
.links(graph.links)
.start();
This final piece of the code defines functions that update attributes on the
nodes and links each time the force calculations update. Note that these
functions reference the data attributes x and y (for example, d.source.x ,
 
Search WWH ::




Custom Search