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 hierarchi
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:
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
g = svg.append("g").attr("transform", "translate(60,0)");
var tree = d3.cluster()
.size([height, width - 160]);
var stratify = d3.stratify()
.parentId(function(d) { return d.id.substring(0, d.id.lastIndexOf(".")); });
d3.json("treeData.json", function(error, treeData) {
if (error) throw error;
var root = d3.hierarchy(treeData);
tree(root);
var link = g.selectAll(".link")
.data(root.descendants().slice(1))
.enter().append("path")
.attr("class", "link")
.attr("d", function(d) {
return "M" + d.y + "," + d.x
+ "C" + (d.parent.y + 100) + "," + d.x
+ " " + (d.parent.y + 100) + "," + d.parent.x
+ " " + d.parent.y + "," + d.parent.x;
});
var node = g.selectAll(".node")
.data(root.descendants())
.enter().append("g")
.attr("class", function(d) { return "node" + (d.children ? " node--internal" : " node--leaf"); })
.attr("transform", function(d) {
return "translate(" + d.y + "," + d.x + ")";
})
node.append("circle")
.attr("r", 2.5);
node.append("text")
.attr("dy", 3)
.attr("x", function(d) { return d.children ? -8 : 8; })
.style("text-anchor", function(d) { return d.children ? "end" : "start"; })
.text(function(d) {
return d.data.name;
});
});
and here's treeData.json
removed from the Array:
{
"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"
}
]
}