Table of Contents

D3 - Stratify (From CSV to tree)

About

With a stratify function, you can turn a series of CSV record in a JSON tree object.

Since v4

Steps

Creating the stratify operator

In the stratify object definition, you may change the following properties:

var stratify = d3.stratify()
    .parentId(function (d) {
        return d.path.substring(0, d.path.lastIndexOf("\\"));
    })
    .id(function (d) {
        return d.path;
    });

Getting the data as CSV

A template string containing the CSV data is passed to the d3.csvParse function. See D3 - DSV

var data = d3.csvParse(`path,size
root,0
root\\child1,10
root\\child2,20
`);
console.log("Data:")
console.log(data)

Creating the tree (By calling the stratify operator)

In this step, you call the stratify operator with the d3 CSV in-memory data representation as parameter to create a tree that will have:

var stratify = d3.stratify()
    .parentId(function (d) {
        return d.path.substring(0, d.path.lastIndexOf("\\"));
    })
    .id(function (d) {
        return d.path;
    });

var data = d3.csvParse(`path,size
root,0
root\\child1,10
root\\child2,20
`);

var root = stratify(data);
console.log(root);

Operations on the tree

Normally, you go further and you call two tree operations (See D3 - Hierarchy):

var stratify = d3.stratify()
    .parentId(function (d) {
        return d.path.substring(0, d.path.lastIndexOf("\\"));
    })
    .id(function (d) {
        return d.path;
    });

var data = d3.csvParse(`path,size
root,0
root\\child1,10
root\\child2,20
`);

var root = stratify(data);

root.sum(function (d) {
            return +d.size;
        })
        .sort(function (a, b) {
            return b.height - a.height || b.value - a.value;
        });

console.log(root);

The details of root are: D3 Stratify Output

Documentation / Reference