I'm trying to update some d3 code from v3 to version 4. I have a tree diagram using JSON data. The d3.v4 examples show how to convert tabular data (e.g. flare.csv) to hierarchical data using stratify() https://bl.ocks.org/mbostock/9d0899acb5d3b8d839d9d613a9e1fe04. But my data is JSON so I don't want or need stratify(). I get this error:
undefined is not a function (evaluating 'root.eachBefore')
running this code:
var height = 200;
var width = 500;
var xNudge = 50;
var yNudge = 20;
var tree = d3.tree()
.size([height, width]);
var svg = d3.select("body").append("svg").attr("width","100%").attr("height","100%");
var chartGroup = svg.append("g").attr("transform","translate(50,200) rotate(-90)");
d3.json("treeData.json", function(treeData) {
var root = treeData[0];
tree(root);
console.log('hello');//doesn't log to console, i.e. error occurs beforehand
}
treeData.json:
[
{
"name": "Top Level",
"parent": "null",
"children": [
{
"name": "Level 2: A",
"parent": "Top Level",
"children": [
{
"name": "Son of A",
"parent": "Level 2: A"
},
{
"name": "Daughter of A",
"parent": "Level 2: A"
}
]
},
{
"name": "Level 2: B",
"parent": "Top Level"
}
]
}
]
Is it actually possible to create a tree layout in d3.v4 without using stratify, i.e. using data that is already hierarchical? Does anyone know of an example, or can spot the problem in my code? thanks
You need to run d3.hierarchy on your data to get it ready for tree(). Stratify presumably runs hierarchy or is similar in some way. So change the appropriate line to: var root = d3.hierarchy(treeData[0]);
I had the same problem. Emma's response essentially answered it, but I still had trouble getting it to work properly. I'll elaborate a bit in case anyone may find it helpful. I created a block showing the functional result here, which is based on your example data above, Emma's response, and this block.
The answer is three parts:
[0]
on the end of your treeData (as Emma did in the link above) to get the Object out of that 1 element Array.d3.hierarchy
(as Emma explained).For convenience, here's the code from the block I made:
and here's
treeData.json
removed from the Array: