Circle Packing

d3 sandwich

Circle Packing

Step #3: Generate the Circle Packing Layout

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.

Here's the code to do all the fancy math needed to figure out where the circles and their labels will go:
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;
  
Create a circle packed layout where:
  • The size of the overall layout is the diameter
  • The layout will use quality to calculate the size of each circle
    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.


Here's the math generated by the the circle packing layout:
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.

Up Next: Recipe Step #4: Create the Groups to Store the Circles and Text