In the previous month's recipe, we used very simple data like the kind you would find in a spreadsheet: one row per state. But what if you have data that has a more complicated structure? A Circle Packing diagram is designed to show data in a hierarchy. In this case, for example, in addition to seeing how many strawberries were sold we also want a rough sense of how many berries or fruit were sold overall. How do we represent that data?
Luckily, D3 is based on JavaScript, and JavaScript has a simple way to show more complex data. It's called the JavaScript Object Notation or JSON. In this Step, we'll learn how to work with it.
To get a rough feel for how JSON works, try changing the names and quantities of a couple of the produce and click Update It to see how the changes affect the Circle Packing graph and the code.
var produce = { name: "produce", children: [ { name: "Veggies", children: [ {name: "Zucchini", quantity: 52}, {name: "Peas", quantity: 30}, {name: "Carrots", quantity: 60}, {name: "Onions", quantity: 70} ] }, { name: "Fruit", children: [ { name: "Berries", children: [ {name: "Raspberries", quantity: 100}, {name: "Strawberries", quantity: 200}, {name: "Blueberries", quantity: 80} ] }, {name: "Apple", quantity: 300}, {name: "Banana", quantity: 200}, ] } ] };
In the Abstract Map recipe, we stored the info about the states in an array or list of objects
var stateMap = [ { state: "ME", row: 0, col: 10 }, { state: "VT", row: 1, col: 9 }, { state: "NH", row: 1, col: 10 }, { state: "WA", row: 2, col: 0 }, { state: "ID", row: 2, col: 1 }, { state: "NY", row: 2, col: 8 } ];
To create a variable that has hierarchical data, we will use a variation of the same trick.
var produce = { name: "produce", children: [ { name: "Veggies", children: [ ... ] } };
{name: "Zucchini", quantity: 52}, {name: "Peas", quantity: 30}, {name: "Carrots", quantity: 60}, {name: "Onions", quantity: 70}
Do the names of the attributes have a special meaning? Nope. You could have used produceName and produceQuantity -- and for that matter produceChildren instead of children -- and it would all still work. So long as your D3 code knows what attribute names you are using, you can use any names you want.
Does it matter if the code is indented? Again, the answer is no; JavaScript and D3 don't care. But if you don't indent the JSON code, it'll be a lot harder to see if there's a problem.