Adding class to root node in d3js tree layout - javascript

I'm playing around with the d3 js tree layout. I was following this example.
I was trying to add class attribute to each of the node. How can i add one class to the root node and a different class to children node.
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("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");
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";
})
.attr("class","node"); // adding class here - common for everything
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);
}
.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;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You can do it like this:
var nodeEnter = node.enter().append("g")
.attr("class", function(d){
if (d.parent == "null"){
return "node parent"//since its root its parent is null
} else
return "node child"//all nodes with parent will have this class
})
.attr("transform", function(d) {
return "translate(" + source.y0 + "," + source.x0 + ")";
})
.on("click", click);
Working code here
Hope this helps

Related

How to make expandable tree in d3.js vertical?

I'm trying to implement an expandable and collapsible tree using d3.js.
But it seems like not working.
Can someone suggest how to fix this?
I mean I'm not being able to expand and toggle it like this demo.
Following is my implementation in vue.js:
var app = new Vue({
el: '#app',
mounted() {
var treeData = {
name: "Top Level",
children: [{
name: "Level 2: A",
children: [{
name: "Son of A",
},
{
name: "Daughter of A",
},
],
},
{
name: "Level 2: B",
},
],
};
// Set the dimensions and margins of the diagram
var margin = {
top: 0,
right: 90,
bottom: 30,
left: 90,
},
width = 960 - margin.left - margin.right,
height = 500 - 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("#tree-graph")
.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(e, d) {
return "translate(" + source.x0 + "," + source.y0 + ")";
})
.on("click", click);
// Add Circle for the nodes
nodeEnter
.append("circle")
.attr("class", "node")
.attr("r", 1e-6)
.style("fill", function(d) {
return d._children ? "lightsteelblue" : "#fff";
});
// Add labels for the nodes
nodeEnter
.append("text")
.attr("dy", ".35em")
.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;
});
// 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.x + "," + d.y + ")";
});
// Update the node attributes and style
nodeUpdate
.select("circle.node")
.attr("r", 10)
.style("fill", function(d) {
return d._children ? "lightsteelblue" : "#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);
});
link
.enter()
.insert("text", "g")
.attr("font-family", "Arial, Helvetica, sans-serif")
.attr("fill", "Orange")
.style("font", "normal 12px Arial")
.attr("transform", function(d) {
return (
"translate(" +
(d.parent.y + d.x) / 2 +
"," +
(d.parent.x + d.y) / 2 +
")"
);
})
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function(d) {
return d.data.name;
});
// 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) {
let path = `M ${s.y} ${s.x}
C ${(s.y + d.x) / 2} ${s.x},
${(s.y + d.x) / 2} ${d.x},
${d.x} ${d.y}`;
return path;
}
// Toggle children on click.
function click(e, d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d);
}
}
}
})
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 3px;
}
.node text {
font: 12px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 2px;
}
<div id="app">
<div id="tree-graph"></div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue#2/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.2.0/d3.js"></script>
All I did was flip the coordinates in the diagonal function from
function diagonal(s, d) {
let 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;
}
to
function diagonal(s, d) {
let path = `M ${s.x} ${s.y}
C ${(s.x + d.x) / 2} ${s.y},
${(s.x + d.x) / 2} ${d.y},
${d.x} ${d.y}`;
return path;
}
Now, the links come out of the side. That is because the example uses the average x of the source s and destination d. To make the links come out of and go into the top and bottom of the nodes, use the following instead:
function diagonal(s, d) {
let path = `M ${s.x} ${s.y}
C ${s.x} ${(s.y + d.y) / 2},
${d.x} ${(s.y + d.y) / 2},
${d.x} ${d.y}`;
return path;
}
And for the labels, you changed (d.parent.y + d.y) / 2 to (d.parent.y + d.x) / 2, but you also need to change which coordinate you take from the parent.
var app = new Vue({
el: '#app',
mounted() {
var treeData = {
name: "Top Level",
children: [{
name: "Level 2: A",
children: [{
name: "Son of A",
},
{
name: "Daughter of A",
},
],
},
{
name: "Level 2: B",
},
],
};
// Set the dimensions and margins of the diagram
var margin = {
top: 0,
right: 90,
bottom: 30,
left: 90,
},
width = 960 - margin.left - margin.right,
height = 500 - 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("#tree-graph")
.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([width, height]);
// Assigns parent, children, height, depth
root = d3.hierarchy(treeData, function(d) {
return d.children;
});
root.x0 = height / 2;
root.y0 = 0;
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(e, d) {
return "translate(" + source.x0 + "," + source.y0 + ")";
})
.on("click", click);
// Add Circle for the nodes
nodeEnter
.append("circle")
.attr("class", "node")
.attr("r", 1e-6)
.style("fill", function(d) {
return d._children ? "lightsteelblue" : "#fff";
});
// Add labels for the nodes
nodeEnter
.append("text")
.attr("dy", ".35em")
.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;
});
// 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.x + "," + d.y + ")";
});
// Update the node attributes and style
nodeUpdate
.select("circle.node")
.attr("r", 10)
.style("fill", function(d) {
return d._children ? "lightsteelblue" : "#fff";
})
.attr("cursor", "pointer");
// Remove any exiting nodes
var nodeExit = node
.exit()
.transition()
.duration(duration)
.attr("transform", function(d) {
return "translate(" + source.x + "," + source.y + ")";
})
.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);
});
link
.enter()
.insert("text", "g")
.attr("font-family", "Arial, Helvetica, sans-serif")
.attr("fill", "Orange")
.style("font", "normal 12px Arial")
.attr("transform", function(d) {
return (
"translate(" +
(d.parent.x + d.x) / 2 +
"," +
(d.parent.y + d.y) / 2 +
")"
);
})
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function(d) {
return d.data.name;
});
// 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) {
let path = `M ${s.x} ${s.y}
C ${(s.x + d.x) / 2} ${s.y},
${(s.x + d.x) / 2} ${d.y},
${d.x} ${d.y}`;
return path;
}
// Toggle children on click.
function click(e, d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d);
}
}
}
})
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 3px;
}
.node text {
font: 12px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 2px;
}
<div id="app">
<div id="tree-graph"></div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue#2/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.2.0/d3.js"></script>

how to append a circle with a label to indicate information to rectangle node and remove the circle before download

I have a vertical D3JS tree where the nodes are rectangles. I would like to append a circle with the italic letter "i" to the top right corner of the rectangle node to indicate that the node has additional information. I managed to append the italic letter "i" only, however, I am not able to put it in a circle and still keep the node clickable. Also I use cloning for downloading the tree as a SVG file and would like to remove this appended circle and the letter "i" from the cloned group element before downloading and printing.
var treeData = [{
"name": "Top Level",
"parent": "null",
"remark": "yes",
"children": [{
"name": "Level 2: A",
"parent": "Top Level",
"remark": "yes",
"children": [{
"name": "Son of A",
"parent": "Level 2: A",
"remark": "null"
},
{
"name": "Daughter of A",
"parent": "Level 2: A",
"remark": "null"
}
]
},
{
"name": "Level 2: B",
"parent": "Top Level",
"remark": "null"
}
]
}];
//*************************************************************************************
// 1. Create the button
var button = document.createElement("button");
button.innerHTML = "download file";
//*************************************************************************************
// ************** 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,
rectW = 100,
rectH = 30,
duration = 750,
root;
var tree = d3.layout.tree()
.size([height, width]);
//swap x and y for vertical
var diagonal = d3.svg.diagonal()
.projection(function(d) {
return [d.x + rectW / 2, d.y + rectH / 2];
// .projection(function(d) { return [d.x, d.y]; });
});
//var gElement = document.createElement('svg:g');
var gElement = document.createElementNS(d3.ns.prefix.svg, 'g');
gElement.setAttribute("id", "fg");
console.log(gElement);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.right + margin.left)
.attr("height", height + margin.top + margin.bottom)
.append(function() {
return gElement;
}) //The argument to .append() has to be a function, you can't just pass element to it.
// .append("svg: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.
//swap x and y for vertical
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) {
return "translate(" + source.x0 + "," + source.y0 + ")";
})
.on("click", click);
nodeEnter.append("rect")
//nodeEnter.append("circle")
// .attr("r", 1e-6)
.attr("width", rectW)
.attr("height", rectH)
.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);
// IAH 20/01/2019 Filter to put tooltip only on nodes that have information associated with it
nodeEnter.filter(function(d) {
return (d.remark != 'null')
})
.append("text")
.attr("id", "infoText")
.attr("x", 96)
.attr("y", 7)
.attr("dy", ".30em")
.style("font-style", "italic")
.style("font-family", "serif")
.style("font-weight", "bold")
.text("i");
// Transition nodes to their new position.
//swap x and y for vertical layout
var nodeUpdate = node.transition()
.duration(duration)
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
//nodeUpdate.select("circle")
nodeUpdate.select("rect")
.attr("width", rectW)
.attr("height", rectH)
.style("stroke", "black")
// .attr("r", 10)
.style("fill", function(d) {
return d._children ? "lightsteelblue" : "#fff";
});
nodeUpdate.select("text")
.attr("x", rectW / 2)
.attr("y", rectH / 2)
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.style("fill-opacity", 1);
// Transition exiting nodes to the parent's new position.
//vertical switch x and y positions
var nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function(d) {
return "translate(" + source.x + "," + source.y + ")";
})
.remove();
//nodeExit.select("circle")
nodeExit.select("rect")
.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", "#ccc")
.attr("fill", "none")
.attr("stroke-width", "2px")
.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);
}
//*************************************************************************************
// 2. Append button somewhere
var body = document.getElementsByTagName("body")[0];
body.appendChild(button)
.setAttribute("transform", "translate(" + 0 + "," + 0 + ")");
//*************************************************************************************
function svgDataURL(svg) {
var svgAsXML = (new XMLSerializer).serializeToString(svg);
var dataURL = "data:image/svg+xml," + encodeURIComponent(svgAsXML);
return dataURL;
}
button.onclick = function() {
var svgElement = document.querySelector('svg');
var svgWH = svgElement.getBBox();
var canvasWidth = svgWH.width;
var canvasHeight = svgWH.height;
var groupElement = document.getElementById('fg');
groupElement.setAttribute("transform", "translate(0,0)");
const bb = groupElement.getBBox();
// clone the svg to avoid destroying it while appending to the svg namespace
let clonedGroupElement = groupElement.cloneNode(true);
var svgContent = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svgContent.setAttribute('viewBox', ' ' + bb.x + ' ' + bb.y + ' ' + bb.width + ' ' + bb.height);
svgContent.setAttribute("width", "100%");
svgContent.setAttribute("height", "100%");
svgContent.setAttribute("preserveAspectRatio", "xMidYMid meet");
// try to remove the information icon before downloading
var rmText = document.getElementById('infoText');
console.log(rmText);
svgContent.appendChild(clonedGroupElement); // use the cloned nodes
var dl = document.createElement('a');
document.body.appendChild(dl);
dl.setAttribute("href", svgDataURL(svgContent)); // function svgDataURL expects a node
dl.setAttribute("download", "test.svg");
dl.click();
dl.remove();
svgContent.removeChild(clonedGroupElement);
};
.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;*/
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
I created a dummy attribute ignore-export and was able to use querySelectorAll() to select all elements with that attribute and remove them. Note that the node.remove() function is not supported in IE, but there is a polyfill available at MDN.
I didn't have any problems with the nodes not responding when I drew the circle, but if you experience it, let me know.
var treeData = [{
"name": "Top Level",
"parent": "null",
"remark": "yes",
"children": [{
"name": "Level 2: A",
"parent": "Top Level",
"remark": "yes",
"children": [{
"name": "Son of A",
"parent": "Level 2: A",
"remark": "null"
},
{
"name": "Daughter of A",
"parent": "Level 2: A",
"remark": "null"
}
]
},
{
"name": "Level 2: B",
"parent": "Top Level",
"remark": "null"
}
]
}];
//*************************************************************************************
// 1. Create the button
var button = document.createElement("button");
button.innerHTML = "download file";
//*************************************************************************************
// ************** 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,
rectW = 100,
rectH = 30,
duration = 750,
root;
var tree = d3.layout.tree()
.size([height, width]);
//swap x and y for vertical
var diagonal = d3.svg.diagonal()
.projection(function(d) {
return [d.x + rectW / 2, d.y + rectH / 2];
// .projection(function(d) { return [d.x, d.y]; });
});
//var gElement = document.createElement('svg:g');
var gElement = document.createElementNS(d3.ns.prefix.svg, 'g');
gElement.setAttribute("id", "fg");
console.log(gElement);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.right + margin.left)
.attr("height", height + margin.top + margin.bottom)
.append(function() {
return gElement;
}) //The argument to .append() has to be a function, you can't just pass element to it.
// .append("svg: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.
//swap x and y for vertical
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) {
return "translate(" + source.x0 + "," + source.y0 + ")";
})
.on("click", click);
nodeEnter.append("rect")
//nodeEnter.append("circle")
// .attr("r", 1e-6)
.attr("width", rectW)
.attr("height", rectH)
.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);
// IAH 20/01/2019 Filter to put tooltip only on nodes that have information associated with it
var nodesWithInfo = nodeEnter.filter(function(d) {
return (d.remark != 'null')
});
nodesWithInfo
.append("circle")
.attr("export-ignore", true)
.attr("cx", 96)
.attr("cy", 7)
.attr("r", 10);
nodesWithInfo
.append("text")
.attr("export-ignore", true)
.attr("id", "infoText")
.attr("x", 96)
.attr("y", 7)
.attr("dy", ".30em")
.style("font-style", "italic")
.style("font-family", "serif")
.style("font-weight", "bold")
.text("i");
// Transition nodes to their new position.
//swap x and y for vertical layout
var nodeUpdate = node.transition()
.duration(duration)
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
//nodeUpdate.select("circle")
nodeUpdate.select("rect")
.attr("width", rectW)
.attr("height", rectH)
.style("stroke", "black")
// .attr("r", 10)
.style("fill", function(d) {
return d._children ? "lightsteelblue" : "#fff";
});
nodeUpdate.select("text")
.attr("x", rectW / 2)
.attr("y", rectH / 2)
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.style("fill-opacity", 1);
// Transition exiting nodes to the parent's new position.
//vertical switch x and y positions
var nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function(d) {
return "translate(" + source.x + "," + source.y + ")";
})
.remove();
//nodeExit.select("circle")
nodeExit.select("rect")
.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", "#ccc")
.attr("fill", "none")
.attr("stroke-width", "2px")
.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);
}
//*************************************************************************************
// 2. Append button somewhere
var body = document.getElementsByTagName("body")[0];
body.appendChild(button)
.setAttribute("transform", "translate(" + 0 + "," + 0 + ")");
//*************************************************************************************
function svgDataURL(svg) {
var svgAsXML = (new XMLSerializer).serializeToString(svg);
var dataURL = "data:image/svg+xml," + encodeURIComponent(svgAsXML);
return dataURL;
}
button.onclick = function() {
var svgElement = document.querySelector('svg');
var svgWH = svgElement.getBBox();
var canvasWidth = svgWH.width;
var canvasHeight = svgWH.height;
var groupElement = document.getElementById('fg');
groupElement.setAttribute("transform", "translate(0,0)");
const bb = groupElement.getBBox();
// clone the svg to avoid destroying it while appending to the svg namespace
let clonedGroupElement = groupElement.cloneNode(true);
var svgContent = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svgContent.setAttribute('viewBox', ' ' + bb.x + ' ' + bb.y + ' ' + bb.width + ' ' + bb.height);
svgContent.setAttribute("width", "100%");
svgContent.setAttribute("height", "100%");
svgContent.setAttribute("preserveAspectRatio", "xMidYMid meet");
// try to remove the information icon before downloading
clonedGroupElement.querySelectorAll('[export-ignore]').forEach(function(node) {
node.remove();
});
svgContent.appendChild(clonedGroupElement); // use the cloned nodes
var dl = document.createElement('a');
document.body.appendChild(dl);
dl.setAttribute("href", svgDataURL(svgContent)); // function svgDataURL expects a node
dl.setAttribute("download", "test.svg");
dl.click();
dl.remove();
svgContent.removeChild(clonedGroupElement);
};
.node {
cursor: pointer;
}
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 3px;
}
.node text {
font: 12px sans-serif;
text-anchor: middle;
}
.link {
/*
fill: none;
stroke: #ccc;
stroke-width: 2px;*/
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>

Place SVG marker in the middle of a curve d3.js

I have a d3 tree layout , on which i have placed marker. The code has been given below.
The marker is defines as :
svg.append("svg:defs")
.append("svg:marker")
.attr("id", "arrow")
.attr("refX", 2)
.attr("refY", 6)
.attr("markerWidth", 13)
.attr("markerHeight", 13)
.attr("orient", "auto")
.append("svg:path")
.attr("d", "M2,2 L2,11 L10,6 L2,2");
Marker is added as:
.attr("marker-start", "url(#arrow)");
But my aim is to add the marker in the centre of the curves ( something like the direction of the curve ) . I cannot use marker-mid since there is no midpoint to the curve. Even if I place it in the centre manipulating X and Y , the orientation will be wrong?
Is there anyway through which this is possible?
Basically all I want is adding direction on a tree layout ( or a curve rather).
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("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 + ")");
svg.append("svg:defs")
.append("svg:marker")
.attr("id", "arrow")
.attr("refX", 20)
.attr("refY", 5)
.attr("markerWidth", 13)
.attr("markerHeight", 13)
.attr("orient", "auto")
.append("svg:path")
.attr("d", "M2,2 L2,11 L10,6 L2,2");
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
});
})
.attr("marker-end", "url(#arrow)");;
// 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);
}
.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;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

How can I include add, edit and delete button to d3 tree layout nodes?

I have generated a tree structure using d3.js which looks like this
But I want to include add,edit and delete button so that tree can be managed dynamically.
Here is one more picture of what I want to include.
Code looks like this:
var treeData =data;
console.log(treeData)
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 [/*width -*/ d.y + 30, d.x + 25]; });
var svg = d3.select("#tree").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 = width-(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")
/!*nodeEnter.append("new-div")*!/
.attr("r", 20)
.style("fill", "#fff");*/
nodeEnter.append("rect")
.attr("width", 100)
.attr("height", 40)
.attr("stroke", "black")
.attr("stroke-width", 1)
.style("fill", function (d) {
return d._children ? "lightsteelblue" : "#fff";
});
/* nodeEnter.append("text")
.attr("y", function(d) {
return d.children || d._children ? -18 : 18; })
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.name; })
.style("fill-opacity", 1);*/
nodeEnter.append("text")
.attr("x", 100 / 2)
.attr("y", 40 / 2)
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function (d) {
return d.name;
});
// 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);
}
In html file I just have
<div id="tree">
</div>
I found a fiddle online and edited it to show you a basic version of what you want : http://jsfiddle.net/reko91/JnNwu/729/
Here is the main code :
var nodeWidth = 300, nodeHeight = 100;
var buttonWidth = nodeWidth/3;
//container
nodeEnter.append("rect")
.attr('class','buttonContainer')
.attr("width", nodeWidth)
.attr("height", nodeHeight)
.style("fill", 'lightsteelblue')
.attr('transform', 'translate(0,'+(-nodeHeight/2)+')');
//buttonAdd
nodeEnter.append("rect")
.attr('class','addButton')
.attr("width", buttonWidth)
.attr("height", nodeHeight/1.5)
.style("fill",'white')
.attr('transform', 'translate(' + nodeHeight/6 + ','+(-nodeHeight/2 + nodeHeight/6)+')')
.on('click', function(d){
console.log('addButton')
})
;
//buttonDelete
nodeEnter.append("rect")
.attr('class','deleteButton')
.attr("width", buttonWidth)
.attr("height", nodeHeight/1.5)
.style("fill",'red')
.attr('transform', 'translate(' + (nodeWidth - buttonWidth- nodeHeight/6 )+ ','+(-nodeHeight/2 + nodeHeight/6)+')')
.on('click', function(d){
console.log('deleteButton')
})
;
What I have done here is, for every node I have appended a container which holds both the add and delete button (you can easily add the edit). On click, they console log their corresponding functions. So the add logs addButton and so on.
Now to implement the proper functionality of each button :)
var json =
{
"name": "Base",
"children": [
{
"name": "Type A",
"children": [
{
"name": "Section 1",
"children": [
{"name": "Child 1"},
{"name": "Child 2"},
{"name": "Child 3"}
]
},
{
"name": "Section 2",
"children": [
{"name": "Child 1"},
{"name": "Child 2"},
{"name": "Child 3"}
]
}
]
},
{
"name": "Type B",
"children": [
{
"name": "Section 1",
"children": [
{"name": "Child 1"},
{"name": "Child 2"},
{"name": "Child 3"}
]
},
{
"name": "Section 2",
"children": [
{"name": "Child 1"},
{"name": "Child 2"},
{"name": "Child 3"}
]
}
]
}
]
};
var width = 700;
var height = 650;
var maxLabel = 150;
var duration = 500;
var radius = 5;
var i = 0;
var 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)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + maxLabel + ",0)");
root = json;
root.x0 = height / 2;
root.y0 = 0;
root.children.forEach(collapse);
function update(source)
{
// Compute the new tree layout.
var nodes = tree.nodes(root).reverse();
var links = tree.links(nodes);
// Normalize for fixed-depth.
nodes.forEach(function(d) { d.y = d.depth * maxLabel; });
// 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);
var nodeWidth = 300, nodeHeight = 100;
var buttonWidth = nodeWidth/3;
//container
nodeEnter.append("rect")
.attr('class','buttonContainer')
.attr("width", nodeWidth)
.attr("height", nodeHeight)
.style("fill", 'lightsteelblue')
.attr('transform', 'translate(0,'+(-nodeHeight/2)+')');
//buttonAdd
nodeEnter.append("rect")
.attr('class','addButton')
.attr("width", buttonWidth)
.attr("height", nodeHeight/1.5)
.style("fill",'white')
.attr('transform', 'translate(' + nodeHeight/6 + ','+(-nodeHeight/2 + nodeHeight/6)+')')
.on('click', function(d){
alert('Add Button : ' + d.name)
console.log('addButton')
})
;
//buttonDelete
nodeEnter.append("rect")
.attr('class','deleteButton')
.attr("width", buttonWidth)
.attr("height", nodeHeight/1.5)
.style("fill",'red')
.attr('transform', 'translate(' + (nodeWidth - buttonWidth- nodeHeight/6 )+ ','+(-nodeHeight/2 + nodeHeight/6)+')')
.on('click', function(d){
alert('Delete Button : ' + d.name)
console.log('deleteButton')
})
;
nodeEnter.append("text")
.attr("x", function(d){
var spacing = computeRadius(d) + 5;
return d.children || d._children ? -spacing : spacing;
})
.attr("dy", "3")
.attr("text-anchor", function(d){ return d.children || d._children ? "end" : "start"; })
.text(function(d){ return d.name; })
.style("fill-opacity", 0);
// 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", function(d){ return computeRadius(d); })
.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", 0);
nodeExit.select("text").style("fill-opacity", 0);
// 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;
});
}
function computeRadius(d)
{
if(d.children || d._children) return radius + (radius * nbEndNodes(d) / 10);
else return radius;
}
function nbEndNodes(n)
{
nb = 0;
if(n.children){
n.children.forEach(function(c){
nb += nbEndNodes(c);
});
}
else if(n._children){
n._children.forEach(function(c){
nb += nbEndNodes(c);
});
}
else nb++;
return nb;
}
function click(d)
{
if (d.children){
d._children = d.children;
d.children = null;
}
else{
d.children = d._children;
d._children = null;
}
update(d);
}
function collapse(d){
if (d.children){
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}
update(root);
html{
font: 10px sans-serif;
}
svg{
border: 1px solid silver;
}
.node{
cursor: pointer;
}
.node circle{
stroke: steelblue;
stroke-width: 1.5px;
}
.link{
fill: none;
stroke: lightgray;
stroke-width: 1.5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id=tree></div>

D3.js Decision Tree - text wraping, bounding box, # of load circles

I'm trying to create a decision tree in D3.
Problems:
- The text goes off the right side, can/how do I set a bounding box to stop that?
The text in the circle isn't wrapping. I am willing to make circles bigger to fit the text, but the wrapping is still a problem.
How do I get only the first 3 circles to show on load?
var treeData = [
{
"name": "TK question here that's long",
"content":"Question here long",
"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 = 860 - 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("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");
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 ? -33 : 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("text")
.attr("x", 0)
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.content; });
// 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", 30)
.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);
}
.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;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Tree Example</title>
</head>
<body>
</body>
</html>
for the wrapping of the text mike bostock covered that in this example: text wrapping in d3 and for the showing of only certain nodes, you should include a filter after the data to show only certain tipes of data (i.e. the nodes that have either no parents or one parent and son (so the first and the middle ones)
you can check this post.. Wrapping text labels also in the foreignObject you can add x and y based on radius of the circle.
var nodeEnter = node.enter().append(\"g\")
.attr(\"class\", \"node\")
.attr(\"transform\", function(d) {
d.radius = (d.x - 90); // add some data to use in ForeignObject
return \"translate(\" + source.y0 + \",\" + source.x0 + \")\";
})
.on(\"click\", click);

Categories

Resources