With the Abstract State Map, we told the browser exactly where to put each state's rectangle and text. Although the commands for doing that looked a little weird the first time we saw them, telling it where they should go was pretty straightforward. But what if you want to create a much more complicated data visualization like our Circle packing graph? Trying to do that by hand would be really painful.
Luckily, D3 has some really powerful built-in functions called "layouts" that'll do all the math for you. In this step, we'll learn how to use the one for Circle packing.
var diameter = 860; var packedLayout = d3.layout.pack() .size([diameter, diameter]) .value(function(d) { return d.quantity; }); var packedNodes = packedLayout.nodes(produce);
As you can see, it only takes a handful of lines.
Use the variable diameter to store the diameter of the entire graph
var diameter = 860;
var packedLayout = d3.layout.pack() .size([diameter, diameter]) .value(function(d) { return d.quantity; });
Do all the fancy math needed for our packed circles by applying the layout to the JSON in produce
var packedNodes = packedLayout.nodes(produce);
You may be wondering, what does the actual math created by the Circle packing layout look like? Let's take a quick peek.
name | x | y | r | children |
---|
FYI, the children column keeps track of whether the object has any children. If you take a look at the graph, you'll notice that the last level -- e.g.,"Peas" -- is a different color then the circles that contain it. That's because peas doesn't have any children. In the next step, we'll show you how that happens.