Search code examples
javascriptd3.jslayouthierarchytreemap

d3 treemap from array without hierarchy


I am trying to create a treemap layout but only with an array of number values. My code simply looks like this (example followed from here):

const data = [32, 16, 37, 56];

const treeMapLayout = d3.treemap().size([400, 200]).paddingOuter(10);
const root = d3.hierarchy(data);

root.sum(d => d.value);
treeMapLayout(root);

d3.select('svg g')
    .selectAll('rect')
    .data(root.descendants())
    .enter()
    .append('rect')
    .attr('x', d => d.x0)
    .attr('y', d => d.y0)
    .attr('width', d => d.x1 - d.x0)
    .attr('height', d => d.y1 - d.y0)
rect {
  fill: cadetblue;
  opacity: 0.3;
  stroke: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width="420" height="220">
  <g></g>
</svg>

Is this possible to do without using d3.hierarchy? Or atleast a way to set this up where I don't need multiple levels?


Solution

  • Yes you can set up a hierarchy that only has 1 level below the root, following the example data in the Hierarchical Layouts section of the page you linked to.

    Here is the data format you need:

    const data = {
        children:[
            {
                value: 32
            },
            {
                value: 16
            },
            {
                value: 37
            },
            {
                value: 56
            },
        ]
    }
    

    Or you can transform it like this:

    const originalData = [32, 16, 37, 56];
    
    const data = {
        children: originalData.map(item => ({value: item}))
    };
    

    Here is a fiddle.