Related
I am working on an angular application with d3. My code is as follows.
var treeData = [{
"name": "MD",
"children": [{
"name": "Professional",
"children": [{
"name": "Third A",
"children": [{
"name": "Fourth A",
"children": [{
"name": "Fifth A"
}, {
"name": "Fifth B"
}, {
"name": "Fifth C"
}, {
"name": "Fifth D"
}]
}, {
"name": "Fourth B"
}, {
"name": "Fourth C"
}, {
"name": "Fourth D"
}]
}, {
"name": "Third B"
}]
}, {
"name": "Leader",
"children": [{
"name": "Third C"
}, {
"name": "Third D"
}]
}, {
"name": "Advocate",
"children": [{
"name": "Third E"
}, {
"name": "Third F"
}]
}, {
"name": "Clinician",
"children": [{
"name": "Third G"
}, {
"name": "Third H"
}, ]
}, ]
}];
var colourScale = d3.scale.ordinal()
.domain(["MD", "Professional", "Leader", "Advocate", "Clinician"])
.range(["#6695c8", "#cd3838", "#d48440", "#a8ba5f", "#63b7c0"]);
// ************** Generate the tree diagram *****************
var margin = {
top: 20,
right: 120,
bottom: 20,
left: 120
},
width = 1200 - margin.right - margin.left,
height = 650 - 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("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];
root.x0 = height / 2;
root.y0 = 0;
update(root);
d3.select(self.frameElement).style("height", "500px");
// 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) {
console.log('UPDATE')
// 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 * 200;
});
// 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 ? "#C0C0C0" : "#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);
nodeEnter.append('foreignObject').attr('width', '20')
.attr("x", 10)
.attr("y", 1)
.attr('height', '20').append('xhtml:input')
.attr('type', 'checkbox')
.attr("id", d => `checkbox-${d.id}`)
//.attr("fill","none")
//.style("opacity","1")
// An on click function for the checkboxes
.on("click", d => {
if (d.children) {
d.children.forEach(child => {
const cb = d3.select(`#checkbox-${child.id}`);
//console.log('CB: ', cb.node());
cb.node().checked = d3.event.target.checked;
cb.attr('disabled', d3.event.target.checked ? true : null);
})
}
else {
if (d3.event.target.checked) {
d.parent.children.forEach(child => {
console.log('CID: ', child.id, d.id);
if (child.id !== d.id) {
const cb = d3.select(`#checkbox-${child.id}`);
console.log('CB: ', cb.node())
cb.node().checked = false;
}
});
}
}
d3.event.stopPropagation();
//console.log(d);
//console.log(d3.event.target.checked);
})
// 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)
.attr("fill-opacity", "0.7")
.attr("stroke-opacity", "1")
.style("fill", function(d) {
return (typeof d._children !== 'undefined') ? (colourScale(findParent(d))) : '#FFF';
})
.style("stroke", function(d) {
return colourScale(findParent(d));
});
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("stroke-width", function(d) {
return 1;
})
.attr("d", function(d) {
var o = {
x: source.x0,
y: source.y0
};
return diagonal({
source: o,
target: o
});
})
.attr("opacity", "0.3")
.style("stroke", function(d) {
return colourScale(findParentLinks(d));
});
// 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;
});
}
function findParent(datum) {
if (datum.depth < 2) {
return datum.name
} else {
return findParent(datum.parent)
}
}
function findParentLinks(datum) {
if (datum.target.depth < 2) {
return datum.target.name
} else {
return findParent(datum.target.parent)
}
}
// 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);
}
.node {
cursor: pointer;
}
.node circle {
fill: #fff;
stroke: #C0C0C0;
stroke-width: 1.5px;
}
.node text {
font: 10px sans-serif;
}
.link {
fill: none;
stroke: #C0C0C0;
stroke-width: 1.5px;
}
I am facing following problem:
If a collapsed node has children, and its parent is getting checked, the node itself is checked as well, but its children cannot be checked because they are not visible.
The checking should work recursively: if a node is checked, all its descendants should be checked and disabled as well regardless their state (expanded or collapsed).
How can I do this?
Here is a proposed solution:
const treeData = {
"id": 1,
"name": "Root",
"checked": false,
"color": "white",
"children": [
{
"id": 2,
"name": "Leaf A",
"checked": false,
"color": "red",
"children": [
{
"id": 3,
"name": "A - 1",
"checked": false,
"color": "brown",
},
{
"id": 4,
"name": "A - 2",
"checked": false,
"color": "orange",
},
{
"id": 5,
"name": "A - 3",
"checked": false,
"color": "yellow",
},
]
},
{
"id": 6,
"name": "Leaf B",
"checked": false,
"color": "green",
"children": [
{
"id": 7,
"name": "B - 1",
"checked": false,
"color": "#00ff40",
},
{
"id": 8,
"name": "B - 2",
"checked": false,
"color": "#00ff80",
}
]
}
]
};
const margin = {
top: 20,
right: 120,
bottom: 20,
left: 120
};
const width = 600 - margin.right - margin.left;
const height = 400 - margin.top - margin.bottom;
var i = 0,duration = 750;
const tree = d3.layout.tree()
.size([height, width]);
const diagonal = d3.svg.diagonal()
.projection(function(d) {
return [d.y, d.x];
});
const svg = d3.select("body").append("svg")
.attr("width", width + margin.right + margin.left)
.attr("height", height + margin.top + margin.bottom);
const container = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
const root = treeData;
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) {
// Compute the new tree layout.
const nodes = tree.nodes(root).reverse();
const links = tree.links(nodes);
// Normalize for fixed-depth.
nodes.forEach(function(d) {
d.y = d.depth * 200;
});
// Update the nodes…
const node = container.selectAll("g.node")
.data(nodes, d => d.id);
// Enter any new nodes at the parent's previous position.
var nodeEnter = node.enter()
.append("g")
.attr("class", "node")
.attr("transform", d => `translate(${source.y0},${source.x0})`)
.on("click", onClickNode);
nodeEnter.append("circle")
.attr("r", 10)
.style("fill", d => d.color);
nodeEnter.append("text")
.attr("x", 20)
.attr("dy", 4)
.attr("text-anchor", "start")
.text(d => d.name);
nodeEnter.append('foreignObject')
.attr('width', '20')
.attr('height', '20')
.attr("x", -30)
.attr("y", -8)
.append('xhtml:input')
.attr('type', 'checkbox')
.attr("id", d => `checkbox-${d.id}`)
.on("click", onClickCheckbox)
// 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")
.style("stroke", 'black');
nodeUpdate.each(function(d) {
const cb = d3.select(this).select('[type="checkbox"]').node();
cb.checked = d.checked;
cb.disabled = isParentChecked(d);
});
nodeUpdate.select("text")
.style("fill-opacity", 1);
// Transition exiting nodes to the parent's new position.
const nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function(d) {
return "translate(" + source.y + "," + source.x + ")";
})
.remove();
nodeExit.select("circle")
.attr("r", 0);
nodeExit.select("text")
.style("fill-opacity", 0);
// Update the links…
var link = container.selectAll("path.link")
.data(links, d => d.target.id);
// Enter any new links at the parent's previous position.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("stroke-width", 1)
.attr("d", function(d) {
var o = {
x: source.x0,
y: source.y0
};
return diagonal({
source: o,
target: o
});
})
.attr("opacity", "0.3")
.style("stroke", 'black');
// 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;
});
}
function findParent(datum) {
if (datum.depth < 2) {
return datum.name
} else {
return findParent(datum.parent)
}
}
function findParentLinks(datum) {
if (datum.target.depth < 2) {
return datum.target.name
} else {
return findParent(datum.target.parent)
}
}
const checkNode = (d, checked, byParent) => {
if (d.id === 2)
console.log('CHECK TO: ', checked);
d.checked = checked;
const children = d.children || d._children;
if (children)
children.forEach(child => checkNode(child, checked, true));
if (!byParent && checked && d.parent) {
console.log('UNCHECK SIBLINGS');
const siblings = d.parent.children || d.parent._children;
siblings.forEach(sibling => {
if (sibling.id !== d.id) {
console.log('UNCHECK: ', sibling)
checkNode(sibling, false, true);
}
});
}
}
function isParentChecked (d) {
if (!d.parent) {
return false;
}
if (d.parent.checked) {
return true;
}
return isParentChecked(d.parent);
}
function onClickCheckbox(d) {
d3.event.stopPropagation();
checkNode(d, d3.event.target.checked, false);
console.log('ROOT: ', root);
update(root);
}
// Toggle children on click.
function onClickNode(d) {
if (d.children) {
d._children = d.children;
d.children = null;
}
else {
d.children = d._children;
d._children = null;
}
update(d);
}
.node {
cursor: pointer;
}
.node circle {
fill: #fff;
stroke: #C0C0C0;
stroke-width: 1.5px;
}
.node text {
font: 10px sans-serif;
}
.link {
fill: none;
stroke: #C0C0C0;
stroke-width: 1.5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
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
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>
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.
I am new to d3 and I am trying to create a collapsible version of https://bl.ocks.org/mbostock/4063550
in v4. There are various examples that explain the same in v3, but I couldn't find a proper one for v4.
I implemented the onClick function in which the children opens up, but the issue is that the links get misplaced after the click. they shift to the right, and the nodes remain at the same position.
Please find below my code for the update function:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
<!--
.node circle {
//fill: #999;
fill: #fff;
stroke: steelblue;
stroke-width: 3px;
}
.node text {
font: 10px sans-serif;
}
.node--internal circle {
fill: #555;
}
.node--internal text {
text-shadow: 0 1px 0 #fff, 0 -1px 0 #fff, 1px 0 0 #fff, -1px 0 0 #fff;
}
.link {
fill: none;
stroke: #555;
stroke-opacity: 0.4;
stroke-width: 1.5px;
}
-->
.node {
cursor: pointer;
}
.node circle {
fill: #999;
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="//d3js.org/d3.v4.min.js"></script>
<script>
var width = 960,
height = 1000,
duration = 750;
var nodes,links;
var i = 0;
var svg = d3.select("body").append("svg")
.attr("width",width)
.attr("height",height);
var g = svg.append("g").attr("transform", "translate(" + (width / 2 + 40) + "," + (height / 2 + 90) + ")");
function connector(d) {
return "M" + project(d.x, d.y)
+ "C" + project(d.x, (d.y + d.parent.y) / 2)
+ " " + project(d.parent.x, (d.y + d.parent.y) / 2)
+ " " + project(d.parent.x, d.parent.y)
/*
return "M" + d.y + "," + d.x +
"C" + (d.y + d.parent.y) / 2 + "," + d.x +
" " + (d.y + d.parent.y) / 2 + "," + d.parent.x +
" " + d.parent.y + "," + d.parent.x; */
}
var treeMap = d3.tree()
.size([360,250]),
root;
var nodeSvg, linkSvg, nodeEnter, linkEnter ;
d3.json("treeData.json",function(error,treeData){
if(error) throw error;
root = d3.hierarchy(treeData,function(d){
return d.children;
});
root.each(function (d) {
console.log(d);
d.name = d.data.name; //transferring name to a name variable
d.id = i; //Assigning numerical Ids
i += i;
});
root.x0 = height / 2;
root.y0 = 0;
function collapse(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}
//root.children.forEach(collapse);
update(root);
});
function update(source) {
//root = treeMap(root);
nodes = treeMap(root).descendants();
//console.log(nodes);
//links = root.descendants().slice(1);
links = nodes.slice(1);
//console.log(links);
var nodeUpdate;
var nodeExit;
// Normalize for fixed-depth.
nodes.forEach(function(d) { d.y = d.depth * 180; });
nodeSvg = g.selectAll(".node")
.data(nodes,function(d) { return d.id || (d.id = ++i); });
//nodeSvg.exit().remove();
var nodeEnter = nodeSvg.enter()
.append("g")
//.attr("class", function(d) { return "node" + (d.children ? " node--internal" : " node--leaf"); })
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + project(d.x, d.y) + ")"; })
//.attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
.on("click",click)
.on("mouseover", function(d) { return "minu"; });
nodeEnter.append("circle")
.attr("r", 5)
.style("fill", color);
nodeEnter.append("text")
.attr("dy", ".31em")
//.attr("x", function(d) { return d.x < 180 === !d.children ? 6 : -6; })
.attr("x", function(d) { return d.children || d._children ? -10 : 10; })
.style("text-anchor", function(d) { return d.x < 180 === !d.children ? "start" : "end"; })
//.attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
.attr("transform", function(d) { return "rotate(" + (d.x < 180 ? d.x - 90 : d.x + 90) + ")"; })
.text(function(d) { return d.data.name; });
// Transition nodes to their new position.
var nodeUpdate = nodeSvg.merge(nodeEnter).transition()
.duration(duration);
// .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });
nodeSvg.select("circle")
.style("fill", color);
nodeUpdate.select("text")
.style("fill-opacity", 1);
// Transition exiting nodes to the parent's new position.
var nodeExit = nodeSvg.exit().transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; }) //for the animation to either go off there itself or come to centre
.remove();
nodeExit.select("circle")
.attr("r", 1e-6);
nodeExit.select("text")
.style("fill-opacity", 1e-6);
nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});
linkSvg = g.selectAll(".link")
.data(links, function(link) { var id = link.id + '->' + link.parent.id; return id; });
// Transition links to their new position.
linkSvg.transition()
.duration(duration);
// .attr('d', connector);
// Enter any new links at the parent's previous position.
linkEnter = linkSvg.enter().insert('path', 'g')
.attr("class", "link")
.attr("d", function(d) {
return "M" + project(d.x, d.y)
+ "C" + project(d.x, (d.y + d.parent.y) / 2)
+ " " + project(d.parent.x, (d.y + d.parent.y) / 2)
+ " " + project(d.parent.x, d.parent.y);
});
/*
function (d) {
var o = {x: source.x0, y: source.y0, parent: {x: source.x0, y: source.y0}};
return connector(o);
});*/
// Transition links to their new position.
linkSvg.merge(linkEnter).transition()
.duration(duration)
.attr("d", connector);
// Transition exiting nodes to the parent's new position.
linkSvg.exit().transition()
.duration(duration)
.attr("d", /*function (d) {
var o = {x: source.x, y: source.y, parent: {x: source.x, y: source.y}};
return connector(o);
})*/function(d) {
return "M" + project(d.x, d.y)
+ "C" + project(d.x, (d.y + d.parent.y) / 2)
+ " " + project(d.parent.x, (d.y + d.parent.y) / 2)
+ " " + project(d.parent.x, d.parent.y);
})
.remove();
// Stash the old positions for transition.
}
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" // collapsed package
: d.children ? "#c6dbef" // expanded package
: "#fd8d3c"; // leaf node
}
function flatten (root) {
// hierarchical data to flat data for force layout
var nodes = [];
function recurse(node) {
if (node.children) node.children.forEach(recurse);
if (!node.id) node.id = ++i;
else ++i;
nodes.push(node);
}
recurse(root);
return nodes;
}
function project(x, y) {
var angle = (x - 90) / 180 * Math.PI, radius = y;
return [radius * Math.cos(angle), radius * Math.sin(angle)];
}
</script>
</body>
</html>
treeData.json:
{
"name": "United States",
"children": [
{
"name": "Arizona",
"children":[
{ "name" : "Arizona Airport", "size": 13}
]
},
{
"name": "California",
"children":[
{"name": "San Francisco","size":15},
{"name": "San Jose","size":25},
{"name": "Los Angeles","size":17}
]
},
{
"name": "Illinois",
"children":[
{ "name" : "Chicago O'Hare", "size": 13},
{ "name" : "Midway", "size": 18 }
]
},
{
"name": "Colorado",
"children" : [
{ "name": "Denver","size": 7}
]
},
{
"name": "Florida","size":2
},
{
"name": "Georgia", "size": 25
},
{
"name": "Kentucky","size":2
},
{
"name": "Massachussets", "size": 25
},
{
"name": "Michigan","size":2
},
{
"name": "Minnesota", "size": 25
},
{
"name": "Missouri","size":2
},
{
"name": "North Carolina", "size": 25
},
{
"name": "Nevada","size":2
},
{
"name": "Newyork", "size": 12
},
{
"name": "Oregon","size":2
},
{
"name": "Pennsylvania", "size": 25
},
{
"name": "Washington",
"children": [
{ "name" : "Seattle","size" : 13}
]
},
{
"name": "Hawaii", "size": 25
},
{
"name": "Texas",
"children" : [
{ "name": "Dallas" ,"size": 9},
{ "name": "Houston" ,"size": 13},
{ "name": "Austin" ,"size": 17}
]
},
{
"name": "Utah", "size": 25
},
{
"name": "Virginia", "size": 25
}
]
}
#Minu didn't update the code in the question, so here's what I did to get it to work:
Just change:
// Transition nodes to their new position.
var nodeUpdate = nodeSvg.merge(nodeEnter).transition()
.duration(duration);
to this:
// Transition nodes to their new position.
var nodeUpdate = nodeSvg.merge(nodeEnter).transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + project(d.x, d.y) + ")"; });
Hopefully this is helpful to someone else who wants to make the radial tree collapsible.