I want to display data in chart.js as a nested treemap using chartjs-chart-treemap.
Everything works fine with flat / single-depth data, but I am having trouble understanding how to make a hierarchical structure work.
I’ve studied the examples but they’ve not given me any clear insight.
Simplified, the data I have is:
- A (50% through children)
- C (25% through children)
- C1 (12.5% through children)
- C1a: 6.25%
- C1b: 6.25%
- C2: 12.5%
- C1 (12.5% through children)
- D: 25%
- C (25% through children)
- B: 50%
This should give a Treemap similar to this:
+-------+------+-------+------+
| C1a | | |
+-------+ C2 | |
| C1b | | |
+-------+------+ B +
| | |
| D | |
| | |
+-------+------+-------+------+
The only thing I have found is to keep adding groups
:
[
{"name": "A", "l0": "/", "l1": "A", "l2": "", "l3": "", "l4": "", "value": 0},
{"name": "B", "l0": "/", "l1": "B", "l2": "", "l3": "", "l4": "", "value": 50},
{"name": "C", "l0": "/", "l1": "A", "l2": "C", "l3": "", "l4": "", "value": 0},
{"name": "C1", "l0": "/", "l1": "A", "l2": "C", "l3": "C1", "l4": "", "value": 0},
{"name": "C1a", "l0": "/", "l1": "A", "l2": "C", "l3": "C1", "l4": "C1a", "value": 6.25},
{"name": "C1b", "l0": "/", "l1": "A", "l2": "C", "l3": "C1", "l4": "C1b", "value": 6.25},
{"name": "C2", "l0": "/", "l1": "A", "l2": "C", "l3": "C2", "l4": "", "value": 12.5},
{"name": "D", "l0": "/", "l1": "A", "l2": "D", "l3": "", "l4": "", "value": 25}
]
But that looks like a hack to me, which would indicate that there is probably a better way to do this?
What I have thus far is:
const data = [
{name: "A", l0: "/", l1: "A", l2: "", l3: "", l4: "", value: 0},
{name: "B", l0: "/", l1: "B", l2: "", l3: "", l4: "", value: 50},
{name: "C", l0: "/", l1: "A", l2: "C", l3: "", l4: "", value: 0},
{name: "C1", l0: "/", l1: "A", l2: "C", l3: "C1", l4: "", value: 0},
{name: "C1a", l0: "/", l1: "A", l2: "C", l3: "C1", l4: "C1a", value: 6.25},
{name: "C1b", l0: "/", l1: "A", l2: "C", l3: "C1", l4: "C1b", value: 6.25},
{name: "C2", l0: "/", l1: "A", l2: "C", l3: "C2", l4: "", value: 12.5},
{name: "D", l0: "/", l1: "A", l2: "D", l3: "", l4: "", value: 25},
];
const ctx = document.querySelector('canvas').getContext("2d");
let config = {
type: 'treemap',
data: {
datasets: [{
tree: data, key: 'value',
groups: ['l0', 'l1', 'l2', 'l3', 'l4', 'name'],
}]
},
};
new Chart(ctx, config);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chartjs-chart-treemap.min.js"></script>
<canvas></canvas>
Is there a better way than just adding groups to achieve nested leafs in the treemap?