Graphics Reference
In-Depth Information
// set up the drawing area
var width = 500,
height = 500;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
In drawing the graph, you can place nodes anywhere in this
500-pixel-by-500-pixel area. So, you first set up some variables to assist in
a layout.
// some variables for layout assistance
var pad = 50;
var num = Math.sqrt(graph.nodes.length);
var scale = (width - pad * 2) / (num);
With this code, you do the following:
• You don't want nodes right on the edge of the drawing area and partially
chopped off, so you allow for some padding around the edges ( pad=50 ).
• A simple layout algorithm is a grid-like layout incrementing the position
of each successive node and wrapping it after reaching the end of line.
Because the code should be generic to handle different graphs, the
number of items per line should depend on the total number of items.
Here, num is set to the square root of the total number of nodes
( graph.nodes.length ). For example, for 4 nodes, the number of
nodes per row will be 2; for 100 items, the number of nodes per row will
be 10.
• The spacing between the items is handled by a scale factor, based on
the number of items to fit in a given width (less the padding on both
sides).
Now, you can create each node in D3 based on the graph.node data.
// draw the nodes
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("circle")
.attr("r", 10)
Search WWH ::




Custom Search