Skip to content

Instantly share code, notes, and snippets.

@d3noob
Last active October 21, 2023 12:33
Show Gist options
  • Save d3noob/8329447 to your computer and use it in GitHub Desktop.
Save d3noob/8329447 to your computer and use it in GitHub Desktop.
D3.js tree diagram generated from external (JSON) data
license: mit

This is a simple d3.js tree diagram that loads an external data file as used as an example in the book D3 Tips and Tricks.

It is derived from the Mike Bostock Collapsible tree example but it is a VERY cut down version without the ability to update (collapse).

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Collapsible Tree Example</title>
<style>
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 3px;
}
.node text { font: 12px sans-serif; }
.link {
fill: none;
stroke: #ccc;
stroke-width: 2px;
}
</style>
</head>
<body>
<!-- load the d3.js library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<script>
// ************** Generate the tree diagram *****************
var margin = {top: 20, right: 120, bottom: 20, left: 120},
width = 960 - margin.right - margin.left,
height = 500 - margin.top - margin.bottom;
var i = 0;
var tree = d3.layout.tree()
.size([height, width]);
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.y, d.x]; });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.right + margin.left)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// load the external data
d3.json("treeData.json", function(error, treeData) {
root = treeData[0];
update(root);
});
function update(source) {
// Compute the new tree layout.
var nodes = tree.nodes(root).reverse(),
links = tree.links(nodes);
// Normalize for fixed-depth.
nodes.forEach(function(d) { d.y = d.depth * 180; });
// Declare the nodes…
var node = svg.selectAll("g.node")
.data(nodes, function(d) { return d.id || (d.id = ++i); });
// Enter the nodes.
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) {
return "translate(" + d.y + "," + d.x + ")"; });
nodeEnter.append("circle")
.attr("r", 10)
.style("fill", "#fff");
nodeEnter.append("text")
.attr("x", function(d) {
return d.children || d._children ? -13 : 13; })
.attr("dy", ".35em")
.attr("text-anchor", function(d) {
return d.children || d._children ? "end" : "start"; })
.text(function(d) { return d.name; })
.style("fill-opacity", 1);
// Declare the links…
var link = svg.selectAll("path.link")
.data(links, function(d) { return d.target.id; });
// Enter the links.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", diagonal);
}
</script>
</body>
</html>
[
{
"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"
}
]
}
]
@EverettBerry
Copy link

Awesome! This really, really helped me.

@remaudga
Copy link

treeData undefined... am I missing something ?

@wakasann
Copy link

Thank you very much!This helped me.

@patidar05priya
Copy link

Hello
Its not working for my json file.

{
"Malaria":
{"children":["Plasmodium sp. LECOR04","Haemoproteus sp. Arg_H9"],
"type": "Disease"},

"Plasmodium sp. LECOR04":
    {"children":["cytb"],
    "type":"organism"},

"Haemoproteus sp. Arg_H9":
    {"children":["cytb"],
    "type":"organism"},

"cytb":{
    "children":["Uganda","Uruguay"],
    "type":"gene"},

"Uganda":{
    "children":[],
    "type":"location"},

"Uruguay":{
    "children":[],
    "type":"Location"},

"Anopheles funestus":{
    "children":["ace-1"],
    "type":"organism"},

"ace-1":{
    "children":["Spain"],
    "type":"gene"},

"Spain":{
    "children":[],
    "type":location"},

"Plasmodium falciparum":{
    "children":["msp3"],
    "type":"organism"},

"msp3":{
    "children":["Italy"],
    "type":"gene"},

"Italy":{
    "children":[],
    "type":"location"},

}

Please help me.

Thanks
Priya

@andrsGutirrz
Copy link

treeData undefined... am I missing something ?

You need to delete the semicolon in the json file

@Vneal006
Copy link

treeData undefined... am I missing something ?

You need to delete the semicolon in the json file

Still getting treeData undefined

@d3noob
Copy link
Author

d3noob commented Jun 10, 2019

I would suggest that you make your JSON file as small as possible so that you can confirm that the problem is either in the JSON or the javascript. Then (assuming that the JSON is the problem) slowly add things somponents to the JSON file untill you strike the part of it that is causing the problem.

@Vneal006
Copy link

Thanks @d3noob for the suggestion it worked to get the data from json to webpage.

I would suggest that you make your JSON file as small as possible so that you can confirm that the problem is either in the JSON or the javascript. Then (assuming that the JSON is the problem) slowly add things somponents to the JSON file untill you strike the part of it that is causing the problem.

@Mhdi-kr
Copy link

Mhdi-kr commented Jan 20, 2023

You can get rid of the "parent" property In JSON file it is not required and actually is redundant in a hierarchical structure such as JSON.

@siva-kumar-s
Copy link

siva-kumar-s commented Mar 29, 2023

it will work for all type of json like '
var Josn = {
"name":"John",
"age":30,
"car":"Benz"
}
form this Json need to create a tree structure
i have tried it not working is there any way to create a tree structure from other type of json structure that you are used for example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment