Question

It looks as though the attribute we use in the JSON to specify the rectangle size must be named "value" otherwise Mike's code at http://bost.ocks.org/mike/treemap/ won't work.

I tried replacing "value" with "amount" in the JSON and changing the Javascript accordingly but that doesn't seem to work. All the rects end up on top of each other at 0,0.

Then I tried specifying the value accessor to use (as per the API docs: https://github.com/mbostock/d3/wiki/Treemap-Layout) by adding an extra line to Mike's example:

var treemap = d3.layout.treemap()
.children(function(d, depth) { return depth ? null : d._children; })  
.sort(function(a, b) { return a.value - b.value; }) 
.ratio(height / width * 0.5 * (1 + Math.sqrt(5)))  
.round(false)  
.value(function(d){ return d.amount; });      // This line added by me

But that didn't get the desired result by itself. (I kept all other references in the code to d.value.)

Can anyone else confirm this? It could trip someone else up too. The documentation (same link as above) says that the JS object nodes all end up with a "value" attribute but I expect that there is a proper way to import a JSON with other names for the numerical field.

Was it helpful?

Solution

If you set the accessor function, it will give the desired results. Here is a FIDDLE with value renamed to amount.

Pertinent sections of code:

...
{"name": "Great Powers", "amount": 3938, ...}, // changed from "value" to "amount"
...

var treemap = d3.layout.treemap()
    .value(function(d) {return d.amount})  // IMPORTANT
    ...
    .sort(function(a, b) { console.log(a.amount); return a.amount - b.amount; })
    ...

function accumulate(d) {
    return (d._children = d.children)
        ? d.amount = d.children.reduce(function(p, v) { return p + accumulate(v); }, 0)
        : d.amount;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top