D3 js - is it possible to draw straight lines between tree nodes? - d3.js

I have created a horizontal tree diagram as shown in below image. I want straight lines between nodes. The curved lines between nodes are default in d3 js. I saw some answers on google for this but did not found any satisfactory result. So is it possible to draw straight lines between nodes in d3 js? If yes then how can I do that?
enter image description here
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">
<script src="https://d3js.org/d3.v3.min.js"></script>
<style>
.node circle {
fill: #ff9900;
stroke: #ff9900;
stroke-width: 1px;
}
.node text {
font: 16px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 2px;
}
</style>
</head>
<body>
<script language="javascript">
var treeData = [{
"name": "1",
"parent": "null",
"children": [{
"name": "2",
"parent": "Persons",
"children": [{
"name": "3",
"parent": "Country of residence"
}, {
"name": "4",
"parent": "Country of residence"
}, {
"name": "5",
"parent": "Country of residence"
}, {
"name": "6",
"parent": "Country of residence"
}]
}]
}];
// ************** 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 line = d3.svg.line()
.x(function(d) {
return d.lx;
})
.y(function(d) {
return d.ly;
});
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 + ")");
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", 40)
.style("fill", "#ff9900");
// append icon inside circle
nodeEnter.append("image")
.attr("xlink:href", "http://localhost/d3/user2.jpg")
.attr("x", "-18px")
.attr("y", "-18px")
.attr("width", "35px")
.attr("height", "35px");
nodeEnter.append("text")
.attr("x", function(d) {
return d.children || d._children ? -40 : -50;
})
.attr("y", function(d) {
return d.children || d._children ? 55 : 55;
})
.attr("dy", ".35em")
.attr("text-anchor", function(d) {
return d.children || d._children ? "start" : "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>
</body>
</html>

Define your line :
var line = d3.svg.line()
.x(function(d) {
return d.y; // because tree is horizontal
})
.y(function(d) {
return d.x; // because tree is horizontal
});
Change your links function to this because d3.svg.line() takes array of points as argument
Hope this helps
// Enter the links.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", function(d) {
return line([d.source, d.target]);
});
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">
<script src="https://d3js.org/d3.v3.min.js"></script>
<style>
.node circle {
fill: #ff9900;
stroke: #ff9900;
stroke-width: 1px;
}
.node text {
font: 16px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 2px;
}
</style>
</head>
<body>
<script language="javascript">
var treeData = [{
"name": "1",
"parent": "null",
"children": [{
"name": "2",
"parent": "Persons",
"children": [{
"name": "3",
"parent": "Country of residence"
}, {
"name": "4",
"parent": "Country of residence"
}, {
"name": "5",
"parent": "Country of residence"
}, {
"name": "6",
"parent": "Country of residence"
}]
}]
}];
// ************** 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 line = d3.svg.line()
.x(function(d) {
return d.y;
})
.y(function(d) {
return 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 + ")");
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", 40)
.style("fill", "#ff9900");
// append icon inside circle
nodeEnter.append("image")
.attr("xlink:href", "http://localhost/d3/user2.jpg")
.attr("x", "-18px")
.attr("y", "-18px")
.attr("width", "35px")
.attr("height", "35px");
nodeEnter.append("text")
.attr("x", function(d) {
return d.children || d._children ? -40 : -50;
})
.attr("y", function(d) {
return d.children || d._children ? 55 : 55;
})
.attr("dy", ".35em")
.attr("text-anchor", function(d) {
return d.children || d._children ? "start" : "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", function(d) { return line([d.source, d.target])});
}
</script>
</body>
</body>
</html>

Related

d3 SVG size is much bigger than what I am setting it as when i publish it on Sharepoint

I have tried searching for an answer to this problem but have not been able to find anything that defines my problem.
I have created an Interactive Tree Diagram Menu for my Sharepoint site using D3.js and HTML (Code Below)
In Codepen it works fine and I can adjust the width and length of the SVG using the width and length variables:
// Set the dimensions and margins of the diagram
var margin = {top: 20, right: 90, bottom: 30, left: 90},
width = 960 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
But no matter what I seem to enter in as the height, once I open this up in a browser the SVG is at least 500px high and taking up way too much empty space.
when I publish this on my Sharepoint site via an iframe, the white space can be even bigger.
I have tried setting the iframe width and height dimensions to 500px, 300px, 100% 50% etc. but it doesn't solve the problem, all it does is mean that you have to scroll within the iframe.
I think it may have something to do with the transform/translate settings in the d3 code but I just can't figure it out - any help would be greatly appreciated!
var treeData =
{
"name": "Board", "url":"Site/Board/SitePages/Home.aspx",
"children": [
{
"name": "Executive",
"url":"Site/Board/Executive/SitePages/Home.aspx",
"children": [
{ "name": "CEO's Office",
"url":"hSite/Board/Executive/CEO/SitePages/Home.aspx"
},
{ "name": "Legal & Integrity",
"url":"Site/Board/Executive/LI/SitePages/Home.aspx",},
{ "name": "Communications & Stakeholder Relations",
"url":"Site/Board/Executive/CGR/SitePages/Home.aspx",},
{ "name": "People & Culture",
"url":"Site/Board/Executive/PC/SitePages/Home.aspx",
"children": [
{"name": "Health, Safety, Environment & Wellbeing",
"url":"Site/Board/Executive/PC/HSEW/SitePages/Home.aspx"
}]},
{"name": "Finance & Risk",
"url":"Site/Board/Executive/FR/SitePages/Home.aspx",
"children": [
{"name":"Financial Risk Register",
"url":"Site/Board/Executive/FR/FIN/SitePages/Home.aspx"}
]
},
{"name":"Volunteers & Strategy",
"url":"Site/Board/Executive/VS/SitePages/Home.aspx"},
{"name":"Infrastructure Services",
"url":"Site/Board/Executive/IS/SitePages/Home.aspx"},
{"name":"Fire & Emergency Management",
"url":"Site/Board/Executive/FEM/SitePages/Home.aspx",
"children":[
{"name":"Bushfire Portfolio",
"url":"Site/Board/Executive/FEM/BP/SitePages/Home.aspx"},
{"name":"Capability & Growth Portfolio",
"url":"Site/Board/Executive/FEM/CGP/SitePages/Home.aspx"},
{"name":"Regional Services Portfolio",
"url":"Site/Board/Executive/FEM/RSP/SitePages/Home.aspx"},
{"name":"Training Portfolio",
"url":"Site/Board/Executive/FEM/TP/SitePages/Home.aspx"},
{"name":"Urban Portfolio",
"url":"Site/Board/Executive/FEM/UP/SitePages/Home.aspx"},
{"name":"South West Region",
"url":"Site/Board/Executive/FEM/SW/SitePages/Home.aspx",
"children":[
{"name":"District 04",
"url":"Site/Board/Executive/FEM/SW/D04/SitePages/Home.aspx"},
{"name":"District 05",
"url":"Site/Board/Executive/FEM/SW/D05/SitePages/Home.aspx"},
{"name":"District 06",
"url":"Site/Board/Executive/FEM/SW/D06/SitePages/Home.aspx"},
{"name":"District 07",
"url":"Site/Board/Executive/FEM/SW/D07/SitePages/Home.aspx"},
]
},
{"name":"West Region",
"url":"Site/Board/Executive/FEM/W/SitePages/Home.aspx",
"children":[
{"name":"District 15",
"url":"Site/Board/Executive/FEM/W/D15/SitePages/Home.aspx"},
{"name":"District 16",
"url":"Site/Board/Executive/FEM/W/D16/SitePages/Home.aspx"},
{"name":"District 17",
"url":"Site/Board/Executive/FEM/W/D17/SitePages/Home.aspx"},
]
},
{"name":"North West Region",
"url":"Site/Board/Executive/FEM/NW/SitePages/Home.aspx",
"children":[
{"name":"District 02",
"url":"Site/Board/Executive/FEM/NW/D02/SitePages/Home.aspx"},
{"name":"District 14",
"url":"Site/Board/Executive/FEM/NW/D14/SitePages/Home.aspx"},
{"name":"District 18",
"url":"Site/Board/Executive/FEM/NW/D18/SitePages/Home.aspx"},
{"name":"District 20",
"url":"Site/Board/Executive/FEM/NW/D20/SitePages/Home.aspx"},
]
},
{"name":"North East Region",
"url":"Site/Board/Executive/FEM/NE/SitePages/Home.aspx",
"children":[
{"name":"District 12",
"url":"Site/Board/Executive/FEM/NE/D12/SitePages/Home.aspx"},
{"name":"District 13",
"url":"Site/Board/Executive/FEM/NE/D13/SitePages/Home.aspx"},
{"name":"District 22",
"url":"Site/Board/Executive/FEM/NE/D22/SitePages/Home.aspx"},
{"name":"District 23",
"url":"Site/Board/Executive/FEM/NE/D23/SitePages/Home.aspx"},
{"name":"District 24",
"url":"Site/Board/Executive/FEM/NE/D24/SitePages/Home.aspx"},
]
},
{"name":"South East Region",
"url":"Site/Board/Executive/FEM/SE/SitePages/Home.aspx",
"children":[
{"name":"District 08",
"url":"Site/Board/Executive/FEM/SE/D08/SitePages/Home.aspx"},
{"name":"District 09",
"url":"Site/Board/Executive/FEM/SE/D09/SitePages/Home.aspx"},
{"name":"District 10",
"url":"Site/Board/Executive/FEM/SE/D10/SitePages/Home.aspx"},
{"name":"District 11",
"url":"Site/Board/Executive/FEM/SE/D11/SitePages/Home.aspx"},
{"name":"District 27",
"url":"Site/Board/Executive/FEM/SE/D27/SitePages/Home.aspx"},
]
},
]
}
]
}
]
};
// Set the dimensions and margins of the diagram
var margin = {top: 20, right: 90, bottom: 30, left: 90},
width = 960 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
// append the svg object to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("#Menu").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 + ")");
var i = 0,
duration = 750,
root;
// declares a tree layout and assigns the size
var treemap = d3.tree().size([height, width]);
// Assigns parent, children, height, depth
root = d3.hierarchy(treeData, function(d) { return d.children; });
root.x0 = height / 2;
root.y0 = 0;
// Collapse after the second level
root.children.forEach(collapse);
update(root);
// Collapse the node and all it's children
function collapse(d) {
if(d.children) {
d._children = d.children
d._children.forEach(collapse)
d.children = null
}
}
function update(source) {
// Assigns the x and y position for the nodes
var treeData = treemap(root);
// Compute the new tree layout.
var nodes = treeData.descendants(),
links = treeData.descendants().slice(1);
// Normalize for fixed-depth.
nodes.forEach(function(d){ d.y = d.depth * 180});
// ****************** Nodes section ***************************
// Update the nodes...
var node = svg.selectAll('g.node')
.data(nodes, function(d) {return d.id || (d.id = ++i); });
// Enter any new modes at the parent's previous position.
var nodeEnter = node.enter().append('g')
.attr('class', 'node')
.attr("transform", function(d) {
return "translate(" + source.y0 + "," + source.x0 + ")";
});
// Add Circle for the nodes
nodeEnter.append('circle')
.attr('class', 'node')
.attr('r', 1e-6)
.style("fill", function(d) {
return d._children ? "#bdc3c7" : "#fff";
})
.on('click', click);
// Add labels for the nodes
nodeEnter.append('text')
.attr("dy", ".30em")
.attr("x", function(d) {
return d.children || d._children ? -13 : 13;
})
.attr("text-anchor", function(d) {
return d.children || d._children ? "end" : "start";
})
.text(function(d) { return d.data.name; })
.attr('class','normalText')
.on('click', hyperclick)
.on('mouseover', function(d,i) {
d3.select(this)
.attr('class', 'bigText')
.style('fill','#c0392b')
;})
.on('mouseout', function(d,i) {
d3.select(this)
.attr('class', 'normalText')
.style('fill','black')
;});
function hyperclick(d) {
window.open(d.data.url);
}
// UPDATE
var nodeUpdate = nodeEnter.merge(node);
// Transition to the proper position for the node
nodeUpdate.transition()
.duration(duration)
.attr("transform", function(d) {
return "translate(" + d.y + "," + d.x + ")";
});
// Update the node attributes and style
nodeUpdate.select('circle.node')
.attr('r', 10)
.style("fill", function(d) {
return d._children ? "#bdc3c7" : "#fff";
})
.attr('cursor', 'pointer');
// Remove any exiting nodes
var nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function(d) {
return "translate(" + source.y + "," + source.x + ")";
})
.remove();
// On exit reduce the node circles size to 0
nodeExit.select('circle')
.attr('r', 1e-6);
// On exit reduce the opacity of text labels
nodeExit.select('text')
.style('fill-opacity', 1e-6);
// ****************** links section ***************************
// Update the links...
var link = svg.selectAll('path.link')
.data(links, function(d) { return d.id; });
// Enter any new links at the parent's previous position.
var linkEnter = link.enter().insert('path', "g")
.attr("class", "link")
.attr('d', function(d){
var o = {x: source.x0, y: source.y0}
return diagonal(o, o)
});
// UPDATE
var linkUpdate = linkEnter.merge(link);
// Transition back to the parent element position
linkUpdate.transition()
.duration(duration)
.attr('d', function(d){ return diagonal(d, d.parent) });
// Remove any exiting links
var linkExit = link.exit().transition()
.duration(duration)
.attr('d', function(d) {
var o = {x: source.x, y: source.y}
return diagonal(o, o)
})
.remove();
// Store the old positions for transition.
nodes.forEach(function(d){
d.x0 = d.x;
d.y0 = d.y;
});
// Creates a curved (diagonal) path from parent to the child nodes
function diagonal(s, d) {
path = `M ${s.y} ${s.x}
C ${(s.y + d.y) / 2} ${s.x},
${(s.y + d.y) / 2} ${d.x},
${d.y} ${d.x}`
return path
}
// Toggle children on click.
function click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<style>
.node circle {
fill: none;
stroke: #c0392b;
stroke-width: 3px;
}
.bigText {
font-family: Sans-Serif;
font-size: 20px;
color: #e74c3c;
text-decoration: underline;
cursor: pointer;
font-style: bold;
}
.normalText {
font-family: Sans-Serif;
font-size: 13px;
color: #000000;
text-decoration: none;
font-style: normal;
}
.link {
fill: none;
stroke: #95a5a6;
stroke-width: 2px;
stroke-length: 1px;
}
</style>
</head>
<body>
<div id="heading"></div>
<div id="Instructions"></div>
<div id="Menu"></div>
<script>
</script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/d3/4.9.1/d3.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
******** BONUS Question **********
Anyone who can tell me to set it up so that three levels of the collapsible tree diagram are shown by default instead of 2 will be awarded 10 internet points!
Have you tried setting the svg width and height attributes to 100%,
and then set the width/height of the containing div (not the iframe)?
This seems to provide consistent results for me. For example, I
changed your JS to: var svg =
d3.select("#Menu").append("svg").attr("width", "100%").attr("height",
"100%").append("g").attr("transform", "translate("+ margin.left + ","
+ margin.top + ")"); and added #Menu { width: 960px; height: 300px; } to your styles. – odin243 Dec 21 at 21:25
This worked a treat

How to expand D3js tree chart onclick a button

I have D3js Tree chart,every thing is working fine but as per my requirement I need to expand whole chart onclick 'Expand' button and collapse again onclick 'collapse' button.It should be same like onclick of 'Top Level' is happening in the chart.Here is code below.Thanks in advance for help.
HTML
<style>
.node {
cursor: pointer;
}
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 3px;
}
.node text {
font: 12px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 2px;
}
</style>
<script src="http://d3js.org/d3.v3.min.js"></script>
<div id="test"></div>
<div id="expand">Expand</div><br><div id="collapse">Collapse</div>
Javascript
var treeData = [
{
"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"
}
]
}
];
// ************** 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,
duration = 750,
root;
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("#test").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 + ")");
root = treeData[0];
root.x0 = height / 2;
root.y0 = 0;
update(root);
d3.select(self.frameElement).style("height", "500px");
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; });
// Update the nodes…
var node = svg.selectAll("g.node")
.data(nodes, function(d) { return d.id || (d.id = ++i); });
// Enter any new nodes at the parent's previous position.
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
.on("click", click);
nodeEnter.append("circle")
.attr("r", 1e-6)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#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", 1e-6);
// Transition nodes to their new position.
var nodeUpdate = node.transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });
nodeUpdate.select("circle")
.attr("r", 10)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
nodeUpdate.select("text")
.style("fill-opacity", 1);
// Transition exiting nodes to the parent's new position.
var nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
.remove();
nodeExit.select("circle")
.attr("r", 1e-6);
nodeExit.select("text")
.style("fill-opacity", 1e-6);
// Update the links…
var link = svg.selectAll("path.link")
.data(links, function(d) { return d.target.id; });
// Enter any new links at the parent's previous position.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", function(d) {
var o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
});
// Transition links to their new position.
link.transition()
.duration(duration)
.attr("d", diagonal);
// Transition exiting nodes to the parent's new position.
link.exit().transition()
.duration(duration)
.attr("d", function(d) {
var o = {x: source.x, y: source.y};
return diagonal({source: o, target: o});
})
.remove();
// Stash the old positions for transition.
nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});
}
// Toggle children on click.
function click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d);
}
Here's an approach to do that:
Add click events using the same logic as in click function by passing the top level data.
// binding events to buttons
d3.select('#expand').on('click', function() {
var topLevelData = treeData.find(function(d) { return d.name === 'Top Level'; });
if(!topLevelData.children) {
click(topLevelData);
}
});
d3.select('#collapse').on('click', function() {
var topLevelData = treeData.find(function(d) { return d.name === 'Top Level'; });
if(topLevelData.children) {
click(topLevelData);
}
});
var treeData = [
{
"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"
}
]
}
];
// ************** 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,
duration = 750,
root;
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("#test").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 + ")");
root = treeData[0];
root.x0 = height / 2;
root.y0 = 0;
update(root);
d3.select(self.frameElement).style("height", "500px");
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; });
// Update the nodes…
var node = svg.selectAll("g.node")
.data(nodes, function(d) { return d.id || (d.id = ++i); });
// Enter any new nodes at the parent's previous position.
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
.on("click", click);
nodeEnter.append("circle")
.attr("r", 1e-6)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#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", 1e-6);
// Transition nodes to their new position.
var nodeUpdate = node.transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });
nodeUpdate.select("circle")
.attr("r", 10)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
nodeUpdate.select("text")
.style("fill-opacity", 1);
// Transition exiting nodes to the parent's new position.
var nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
.remove();
nodeExit.select("circle")
.attr("r", 1e-6);
nodeExit.select("text")
.style("fill-opacity", 1e-6);
// Update the links…
var link = svg.selectAll("path.link")
.data(links, function(d) { return d.target.id; });
// Enter any new links at the parent's previous position.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", function(d) {
var o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
});
// Transition links to their new position.
link.transition()
.duration(duration)
.attr("d", diagonal);
// Transition exiting nodes to the parent's new position.
link.exit().transition()
.duration(duration)
.attr("d", function(d) {
var o = {x: source.x, y: source.y};
return diagonal({source: o, target: o});
})
.remove();
// Stash the old positions for transition.
nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});
}
// Toggle children on click.
function click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d);
}
// binding events to buttons
d3.select('#expand').on('click', function() {
var topLevelData = treeData.find(function(d) { return d.name === 'Top Level'; });
if(!topLevelData.children) {
click(topLevelData);
}
});
d3.select('#collapse').on('click', function() {
var topLevelData = treeData.find(function(d) { return d.name === 'Top Level'; });
if(topLevelData.children) {
click(topLevelData);
}
});
<style>
.node {
cursor: pointer;
}
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 3px;
}
.node text {
font: 12px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 2px;
}
</style>
<script src="https://d3js.org/d3.v3.min.js"></script>
<div id="test"></div>
<div id="expand">Expand</div><br><div id="collapse">Collapse</div>
Hope this helps.

Indented Tree using D3.js V4

I'm trying to display a indented tree view using D3.js V4 but for some reason I can't make the rectangles to display in the right order(parent-child relationship).
The Level 2:B should be displayed at the same x position as the Level 2:A but the position of the y seems to be wrong.What I expect would be something like this:
Treeview Image
Can somebody please tell me what I'm doing wrong?
I'm new to D3 so apologize in advance.
Here's a snippet with my code:
var treeData =
{
"name": "Top Level",
"parent": "null",
"children": [
{
"name": "Level 2: A",
"parent": "Top Level",
"children": [
{
"name": "Son of A",
"parent": "Level 2: A",
"children" : [
{
"name": "child of Son",
"parent": "Son of A"
}
]
},//children
{
"name": "Daughter of A",
"parent": "Level 2: A"
}
]
},
{
"name": "Level 2: B",
"parent": "Top Level"
}
]
}
var margin = {top: 30, right: 20, bottom: 30, left: 20},
width = 960 - margin.left - margin.right,
barHeight = 30,
barWidth = width * .1;
height = 600;
var i = 0,
duration = 400,
root;
var tree = d3.tree()
.nodeSize([0, 20]);
var svg = d3.select("body").append("svg")
.attr('viewBox', '0 -10 '+ width + " " + 500)
//.attr("width", width + margin.left + margin.right)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var root = d3.hierarchy(treeData, function (d) { return d.children;});
update(root);
function update(source) {
// Compute the flattened node list. TODO use d3.layout.hierarchy.
nodes = tree(root).descendants();
console.log(nodes)
var height = Math.max(500, nodes.length * barHeight + margin.top + margin.bottom);
d3.select("svg").transition()
.duration(duration)
.attr("height", height);
// Compute the "layout".
nodes.forEach(function (n,i) {
n.x = i * 30;
});
// Update the nodes…
var node = svg.selectAll("g.node")
.data(nodes, function(d) { return d.id || (d.id = ++i); });
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
.style("opacity", 1e-6);
// Enter any new nodes at the parent's previous position.
nodeEnter.append("rect")
.attr("y", -barHeight / 2)
.attr("height", barHeight)
.attr("width", barWidth)
.style("fill", color)
.on("click", click);
nodeEnter.append("text")
.attr("dy", 3.5)
.attr("dx", 5.5)
.text(function (d) {
return d.depth == 0 ? d.data.name + " >>>" : d.depth == 1 ? d.data.name + " >>" : d.data.name ; });
// Transition nodes to their new position.
nodeEnter.transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
.style("opacity", 1);
node.transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
.style("opacity", 1)
.select("rect")
.style("fill", color);
// Transition exiting nodes to the parent's new position.
node.exit().transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
.style("opacity", 1e-6)
.remove();
nodes.forEach(function (d) {
d.x0 = d.x;
d.y0 = d.y
});
}
// Toggle children on click.
function click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d);
}
function color(d) {
return d._children ? "#3182bd" : d.children ? "#c6dbef" : "lightgreen";
}
.node rect {
cursor: pointer;
fill: #fff;
fill-opacity: .5;
stroke: #3182bd;
stroke-width: 1px;
}
.node text {
font: 10px sans-serif;
pointer-events: none;
}
path.link {
fill: none;
stroke: #9ecae1;
stroke-width: 1.5px;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<body></body>

Network of pie charts with legend or tooltip?

I am working on plotting a network of pie charts and I have been working all weekend to try and put either a legend or a tooltip for each pie wedge. Here is my working Fiddle without labels and I have pasted the code below. How do I either put in the group numbers or labels from the labels variable?
Thanks in advance!!
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
<style>
.node {
stroke: #fff;
stroke-width: 1.5px;
}
.link {
stroke: #808080;
stroke-opacity: .6;
}
</style>
</head>
<body>
<script type="text/javascript">
graph = { "nodes":[{"proportions": [
{"group":1, "value": 25 },
{"group":2, "value": 0 },
{"group":3, "value": 0 },
{"group":4, "value": 0 }],"radius":25,"x":1000,"y":262.5},{"proportions": [
{"group":1, "value": 0 },
{"group":2, "value": 25 },
{"group":3, "value": 0 },
{"group":4, "value": 0 }],"radius":25,"x":191.3501125,"y":70.44565171875},{"proportions": [
{"group":1, "value": 0 },
{"group":2, "value": 0 },
{"group":3, "value": 25 },
{"group":4, "value": 0 }],"radius":25,"x":25,"y":30.9375},{"proportions": [
{"group":1, "value": 0 },
{"group":2, "value": 0 },
{"group":3, "value": 0 },
{"group":4, "value": 25 }],"radius":25,"x":833.572375,"y":222.9734390625}],"links": [{ "source":0, "target":1, "length":900, "width":9},
{ "source":0, "target":3, "length":900, "width":9},
{ "source":1, "target":2, "length":900, "width":9},
{ "source":2, "target":3, "length":900, "width":9}]
}
var labels = ['mycave1','mycave2','mycave3','mycave4'];
var width = 4000,
height = 1000,
radius = 25,
color = d3.scale.category10();
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.value; });
var arc = d3.svg.arc()
.outerRadius(radius)
.innerRadius(0);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var force = d3.layout.force()
.charge(-120)
.linkDistance(4 * radius)
.size([width, height]);
force.nodes(graph.nodes)
.links(graph.links)
.start();
var link = svg.selectAll(".link")
.data(graph.links)
.enter().append("line")
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; })
.attr("class", "link");
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"});
node.each(function(d){
arc = arc.outerRadius(d.radius);
d3.select(this)
.selectAll("path")
.data(function(d){ return pie(d.proportions); })
.enter().append("svg:path")
.attr("d", arc)
.style("fill", function(d,i){ return color(d.data.group) });
});
</script>
</body>
</html>
For tooltips, just append a title element to each path.
.append("svg:title")
.text(function(d) {return "Group "+d.data.group;});
Here's a fiddle: http://jsfiddle.net/ctsprjyq/18/
If you want the corresponding labels instead (Group 1=mycave1, Group 2=mycave2, etc.), just use the group value as an index to the labels array.
.append("svg:title")
.text(function(d) {return labels[d.data.group-1];});

A tree that combines horizontal and vertical layouts

I'm trying to create a D3 tree that consists of both horizontal and vertical orientations. I want the first and second levels of the tree to be horizontal and then each following level to be vertical under its parent. Here is the result I got so far:
http://jsfiddle.net/z3UX6/17/
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.node {
cursor: pointer;
}
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 1.5px;
}
.node text {
font: 10px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 1.5px;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var margin = {
top: 20,
right: 120,
bottom: 20,
left: 120
},
width = 960 - margin.right - margin.left,
height = 800 - margin.top - margin.bottom;
var i = 0,
duration = 750,
root;
var tree = d3.layout.tree()
.size([height, width]);
var diagonal = d3.svg.diagonal()
.projection(function (d) {
return d.depth < 2 ? [d.x, d.y] : [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 + ")");
root = {
"name": "Homepage",
"children": [{
"name": "test1",
"children": [{
"name": "page",
}, {
"name": "page",
}, {
"name": "page",
}, {
"name": "page",
}, {
"name": "page",
}]
}, {
"name": "test2",
"children": [{
"name": "page",
}, {
"name": "page",
}, {
"name": "page",
}, {
"name": "page",
}, {
"name": "page",
}]
}, {
"name": "test3",
"children": [{
"name": "page",
}, {
"name": "page",
}, {
"name": "page",
}, {
"name": "page",
}, {
"name": "page",
}]
}, {
"name": "test4",
"children": [{
"name": "page",
}, {
"name": "page",
}, {
"name": "page",
}, {
"name": "page",
}, {
"name": "page",
}]
}]
};
root.x0 = height / 2;
root.y0 = 0;
function collapse(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}
update(root);
d3.select(self.frameElement).style("height", "800px");
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) {
if (d.depth < 2) {
d.y = d.depth * 100
}
else {
d.y = d.parent.x;
}
});
// Update the nodes…
var node = svg.selectAll("g.node")
.data(nodes, function (d) {
return d.id || (d.id = ++i);
});
// Enter any new nodes at the parent's previous position.
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function (d) {
return "translate(" + source.y0 + "," + source.x0 + ")";
})
.on("click", click);
nodeEnter.append("circle")
.attr("r", 1e-6)
.style("fill", function (d) {
return d._children ? "lightsteelblue" : "#fff";
});
nodeEnter.append("text")
.attr("x", function (d) {
return d.children || d._children ? -10 : 10;
})
.attr("dy", ".35em")
.attr("text-anchor", function (d) {
return d.children || d._children ? "end" : "start";
})
.text(function (d) {
return d.name;
})
.style("fill-opacity", 1e-6);
// Transition nodes to their new position.
var nodeUpdate = node.transition()
.duration(duration)
.attr("transform", function (d) {
return d.depth < 2 ? "translate(" + d.x + "," + d.y + ")" : "translate(" + d.y + "," + d.x + ")";
});
nodeUpdate.select("circle")
.attr("r", 4.5)
.style("fill", function (d) {
return d._children ? "lightsteelblue" : "#fff";
});
nodeUpdate.select("text")
.style("fill-opacity", 1);
// Transition exiting nodes to the parent's new position.
var nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function (d) {
return "translate(" + source.y + "," + source.x + ")";
})
.remove();
nodeExit.select("circle")
.attr("r", 1e-6);
nodeExit.select("text")
.style("fill-opacity", 1e-6);
// Update the links…
var link = svg.selectAll("path.link")
.data(links, function (d) {
return d.target.id;
});
// Enter any new links at the parent's previous position.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", function (d) {
var o = {
x: source.x0,
y: source.y0
};
return diagonal({
source: o,
target: o
});
});
// Transition links to their new position.
link.transition()
.duration(duration)
.attr("d", diagonal);
// Transition exiting nodes to the parent's new position.
link.exit().transition()
.duration(duration)
.attr("d", function (d) {
var o = {
x: source.x,
y: source.y
};
return diagonal({
source: o,
target: o
});
})
.remove();
// Stash the old positions for transition.
nodes.forEach(function (d) {
d.x0 = d.x;
d.y0 = d.y;
});
}
// Toggle children on click.
function click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d);
}
</script>
As you could see the 3rd level is not actually positioned under the parent, although I managed to put it in the same "column" as a parent, but the vertical level is not correct. Also links are all gone crazy. This I can't figure out at all.

Resources