Wrapping long text labels in D3 without extra new lines [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Utilizing Mike Bostock’s Wrapping Long Labels function I was able to wrap long text labels in D3.js. However I see that my D3 chart inserts extra new lines when a particular text needs to be wrapped into more than two lines. Can you please help me to wrap without these extra new lines?
Here are my label data and Mike Bostock’s code I used.
treeData = {
'name': 'Good Short Label',
'parent': 'null',
'_children': [
{'name': 'Very Very Long Good Wapped Label'},
{'name': 'Very Very Very Very Very Very Very Very Very Long Label With Extra New Line'},
{'name': 'Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Long Label With Extra New Lines'}
]
};
function wrap(text, width) {
text.each(function () {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
x = text.attr('x'),
y = text.attr('y'),
dy = 0, //parseFloat(text.attr('dy')),
tspan = text.text(null)
.append('tspan')
.attr('x', x)
.attr('y', y)
.attr('dy', dy + 'em');
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(' '));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(' '));
line = [word];
tspan = text.append('tspan')
.attr('x', x)
.attr('y', y)
.attr('dy', ++lineNumber * lineHeight + dy + 'em')
.text(word);
}
}
});
}
Here is the jsfiddle link to replicate this.

Just don't increment the lineHeight variable
.attr('dy', ++lineNumber * lineHeight + dy + 'em') // add a newline multiple times
.attr('dy', lineHeight + dy + 'em') // adds only one new line
var treeData = {
'name': 'Good Short Label',
'parent': 'null',
'_children': [
{'name': 'Very Very Long Good Wapped Label'},
{'name': 'Very Very Very Very Very Very Very Very Very Long Label With Extra New Line'},
{'name': 'Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Very Long Label With Extra New Lines'}
]
};
var margin = {top: 20, right: 120, bottom: 20, left: 200};
var width = 950 - margin.right - margin.left;
var height = 800 - margin.top - margin.bottom;
var i = 0;
var duration = 750;
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('#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;
root.x0 = height / 2;
root.y0 = 0;
update(root);
d3.select(self.frameElement).style('height', '800px');
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 * 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 ? '#ccff99' : '#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;
})
.call(wrap, 150)
.style('fill-opacitsy', 1e-6)
.attr('class', function (d) {
if (d.url != null) {
return 'hyper';
}
})
.on('click', function (d) {
$('.hyper').attr('style', 'font-weight:normal');
d3.select(this).attr('style', 'font-weight:bold');
})
;
// 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 ? '#ccff99' : '#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);
}
function wrap(text, width) {
text.each(function () {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
x = text.attr('x'),
y = text.attr('y'),
dy = 0, //parseFloat(text.attr('dy')),
tspan = text.text(null)
.append('tspan')
.attr('x', x)
.attr('y', y)
.attr('dy', dy + 'em');
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(' '));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(' '));
line = [word];
tspan = text.append('tspan')
.attr('x', x)
.attr('y', y)
.attr('dy', lineHeight + dy + 'em')
.text(word);
}
}
});
}
#vid-container {
width: 100%;
height: 100%;
width: 820px;
height: 461.25px;
float: none;
clear: both;
margin: 2px auto;
}
svg {
border-radius: 3px;
}
.node {
cursor: pointer;
}
.node circle {
fill: #fff;
stroke: #99ccff;;
stroke-width: 3px;
}
.node text {
font: 12px sans-serif;
}
.link {
fill: none;
stroke: #99ccff;
stroke-width: 2px;
}
.hyper {
color: red;
text-decoration: underline;
}
.hyper:hover {
color: yellow;
text-decoration: none;
}
.selected {
font-weight: bold;
}
.not-selected {
font-weight: normtal;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id='tree'></div>

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 use d3plus.TextBox() module for SVG line wrapping and automatic font size scaling ( on a D3.js Hierarchy Tree)

I am trying to use textBox module of d3plus-text for SVG textbox line-wrapping and automatic font size-scaling. I am following the use instructions from here https://github.com/d3plus/d3plus-text#d3plus-text
I am using the fucntion like so (as reccomended in the github) after updating the root tree:
new d3plus.TextBox()
.data(d3.select("text#rectResize"))
.fontSize(16)
.width(200)
.x(function(d, i) { return i * 250; })
.render();
But I am running into problems with the following error message:
d3plus-text.v0.10.full.min.js:7 Uncaught (in promise) TypeError: this._data.reduce is not a function
at i.a (d3plus-text.v0.10.full.min.js:7)
at test6.html:86
I have searched high and low but still not been able to make this work. Any help on this would be appreciated.
PS: I know I can use MikeBostics Wrap functionality which you can see I have used in the code below with some edits and it works. But I still want to learn how to use d3plus.TextBox as it seems more elegant and provides additional functionality.
Shorter version of my script is below. You can fiddle with it here
<!DOCTYPE html>
<meta charset="UTF-8">
<!-- load the d3.js library -->
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="https://d3plus.org/js/d3plus-text.v0.10.full.min.js"></script>
<style>
.node circle {
fill: #FFF;
stroke: #009BE4;
stroke-width: 2px;
}
.node text {
font: 12px sans-serif;
}
.link {
fill: none;
stroke: #555;
stroke-width: 2px;
stroke-opacity: 0.3;
}
</style>
<body>
<script>
const circleSize = 8
// Set the dimensions and margins of the diagram
var margin = {top: 20, right: 90, bottom: 30, left: 90},
width = 900 - margin.left - margin.right,
height = 900 - margin.top - margin.bottom;
// declares a tree layout and assigns the size
var treemap = d3.tree().size([height, width]);
// load the external data
var flatData = [
{"name": "This is a very long name for the top level", "parent": null},
{"name": "This is a very long name for Level 2A", "parent": "This is a very long name for the top level" },
{"name": "This is a very long name for Level 2B", "parent": "This is a very long name for the top level" },
{"name": "This is a very long name for Son of A", "parent": "This is a very long name for Level 2A" },
{"name": "This is a very long name for Daughter of A", "parent": "This is a very long name for Level 2A" }
];
// assign null correctly
flatData.forEach(function(d) {
if (d.parent == "null") { d.parent = null};
});
// convert the flat data into a hierarchy
var treeData = d3.stratify()
.id(function(d) { return d.name; })
.parentId(function(d) { return d.parent; })
(flatData);
// assign the name to each node
treeData.each(function(d) {
d.name = d.data.name;
});
// 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("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 + ")");
var i = 0,
duration = 500,
root;
// 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);
new d3plus.TextBox()
.data(d3.select("text#rectResize"))
.fontSize(16)
.width(200)
.x(function(d, i) { return i * 250; })
.render();
// wrap text - not elegant way to wrap text
function wrap2(text, width) {
text.each(function() {
var text = d3.select(this),
// words = text.text().split(/\s+/).reverse(), In order to prevent cutting through non-breaking spaces, replaced by below
words = text.text().split(/[ \f\n\r\t\v]+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.2, // ems
y = text.attr("y"),
x = text.attr("x"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", x).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", x).attr("y", y).attr("dy", lineHeight + "em").text(word);
}
}
// find corresponding rect and reszie
d3.select(this.parentNode.children[0]).attr('height', 19 * (lineNumber+1));
});
}
// 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 + ")";
})
.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("id", "rectResize")
.attr("dy", "0em")
/* .attr("x", d => d.children ? -15 : 15) */
// .attr("text-anchor", d => d.children ? "end" : "start")
.attr("x", function(d) {
return d.children || d._children ? -15 : 15;
})
.attr("text-anchor", function(d) {
return d.children || d._children ? "end" : "start";
})
.text(function(d) { return d.data.name; })
.style("fill-opacity", 1)
// .call(wrap, 150)
.clone(true).lower()
.attr("stroke", "white");
// 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', circleSize)
.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)
});
// 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>
</body>

D3 version 4 tree view with rectangle nodes links not showing up

I'm working on d3.js version 4 and angular 5 to build treeview. I found Treeview with circular nodes example(Example Here). But i changed circular nodes to rectangle.Now links are not showing up in tree.
Image of tree view with rectangle nodes and not showing links from parent to child.
Image of Tree view with expanded nodes.
Component.ts :
import { Component, OnInit, ViewEncapsulation } from '#angular/core';
import * as d3 from 'd3';
#Component({
selector: 'app-rec-tree-view',
templateUrl: './rec-tree-view.component.html',
styleUrls: ['./rec-tree-view.component.css'],
encapsulation: ViewEncapsulation.None
})
export class RecTreeViewComponent implements OnInit {
margin = { top: 20, right: 120, bottom: 20, left: 120 };
width = 1200 - this.margin.right - this.margin.left;
height = 1200 - this.margin.top - this.margin.bottom;
tree = d3.tree().size([this.height, this.width]);
i = 0;
duration = 750;
root;
svg;
g;
constructor() { }
ngOnInit() {
this.loadChart();
}
loadChart() {
this.svg = d3.select('#treeView').append('svg')
.attr('width', this.width + this.margin.right + this.margin.left)
.attr('height', this.height + this.margin.top + this.margin.bottom)
.append('g')
.attr('transform', 'translate(' + this.margin.left + ',' + this.margin.top
+ ')');
this.root = d3.hierarchy(this.treeData, (d: any) => d.children);
this.root.x0 = 0;
this.root.y0 = this.height / 2;
this.root.children.forEach(this.collapse);
this.update(this.root);
}
collapse = (d) => {
if (d.children) {
d._children = d.children;
d._children.forEach(this.collapse);
d.children = null;
}
}
update(source) {
const treeData = this.tree(this.root);
const nodes = treeData.descendants(),
links = treeData.descendants().slice(1);
nodes.forEach((d) => { d.y = d.depth * 180; });
const node = this.svg.selectAll('g.node')
.data(nodes, (d) => d.id || (d.id = ++this.i));
const nodeEnter = node.enter().append('g')
.attr('class', 'node')
.attr('transform', (d) => 'translate(' + source.y0 + ',' + source.x0 +
')')
.on('click', this.click);
nodeEnter.append('rect')
.attr('width', 1e-6)
.attr('height', 1e-6)
.style('fill', function (d: any) {
return d._children ? 'lightsteelblue' : '#fff';
});
nodeEnter.append('text')
.attr('dy', '.35em')
.attr('x', -10)
.text(function (d: any) { return d.data.name; });
const nodeUpdate = nodeEnter.merge(node);
nodeUpdate.transition()
.duration(this.duration)
.attr('transform', (d) => 'translate(' + d.y + ',' + d.x + ')');
const nodeHeight = 40,
nodeWidth = 150;
nodeUpdate.select('rect')
.attr('rx', 6)
.attr('ry', 6)
.attr('y', -(nodeHeight / 2))
.attr('width', nodeWidth)
.attr('height', nodeHeight)
.style('fill', (d) => d._children ? 'lightsteelblue' : '#fff');
nodeUpdate.select('text')
.style('fill-opacity', 1);
const nodeExit = node.exit().transition()
.duration(this.duration)
.attr('transform', (d) => 'translate(' + source.y + ',' + source.x + ')')
.remove();
nodeExit.select('rect')
.attr('width', 1e-6)
.attr('height', 1e-6);
nodeExit.select('text')
.style('fill-opacity', 1e-6);
const link = this.svg.selectAll('path.link')
.data(links, (d) => d.id);
const linkEnter = link.enter().insert('path', 'g')
.attr('class', 'link')
.attr('d', (d) => {
const o = { x: source.x0, y: source.y0 };
return this.diagonal(o, o);
});
link.transition()
.duration(this.duration)
.attr('stroke', 'black')
.attr('d', this.diagonal);
link.exit().transition()
.duration(this.duration)
.attr('stroke', 'black')
.attr('d', (d) => {
const o = { x: source.x, y: source.y };
return this.diagonal(o, o);
})
.remove();
nodes.forEach((d) => {
d.x0 = d.x;
d.y0 = d.y;
});
}
click = (d) => {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
this.update(d);
}
diagonal(s, d) {
const 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;
}
}
css
.node {
cursor: pointer;
}
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 1.5px;
}
.node text {
font: 10px sans-serif;
}
.link {
fill: none;
stroke: rgb(236, 32, 5);
stroke-width: 1.5px;
}
.node rect {
fill: none;
stroke: #636363;
stroke-width: 1.5px;
}
Looks like you missed the "Link Update" section of the example code:
// 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) });
You may want to read up on the changes to selections that are in D3V4 -- Note especially that this D3V3 append() behavior has been deprecated:
In addition, selection.append no longer merges entering nodes into the
update selection; use selection.merge to combine enter and update
after a data join.

Tree with children towards multiple side in d3.js (similar to family tree)

var treeData = [{
"name": "Device",
"parent": "null"
}
];
var treeData2 = [{
"name": "Device",
"parent": "null"
}
];
$(document).ready(function() {
var margin = {
top: 20,
right: 120,
bottom: 20,
left: 120
},
width = 1260 - 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);
makeRightTree();
makeLeftTree();
});
function makeRightTree() {
// ************** Generate the tree diagram *****************
var margin = {
top: 20,
right: 120,
bottom: 20,
left: 120
},
width = 1260 - 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("svg").append("g")
.attr("transform", "translate(600,0)");
root = treeData[0];
root.x0 = height / 2;
root.y0 = 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;
});
// 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", function(d) {
if (d.parent == "null") {
return "node rightparent" //since its root its parent is null
} else
return "node rightchild" //all nodes with parent will have this class
})
.attr("transform", function(d) {
return "translate(" + source.y0 + "," + source.x0 + ")";
})
.on("click", click);
nodeEnter.append("rect")
.attr("x", "-10")
.attr("y", "-15")
.attr("height", 30)
.attr("width", 100)
.attr("rx", 15)
.attr("ry", 15)
.style("fill", "#f1f1f1");
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);
var addRightChild = nodeEnter.append("g");
addRightChild.append("rect")
.attr("x", "90")
.attr("y", "-10")
.attr("height", 20)
.attr("width", 20)
.attr("rx", 10)
.attr("ry", 10)
.style("stroke", "#444")
.style("stroke-width", "2")
.style("fill", "#ccc");
addRightChild.append("line")
.attr("x1", 95)
.attr("y1", 1)
.attr("x2", 105)
.attr("y2", 1)
.attr("stroke", "#444")
.style("stroke-width", "2");
addRightChild.append("line")
.attr("x1", 100)
.attr("y1", -4)
.attr("x2", 100)
.attr("y2", 6)
.attr("stroke", "#444")
.style("stroke-width", "2");
// 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
});
}).on("click", removelink);
function removelink(d) {
//this is the links target node which you want to remove
var target = d.target;
//make new set of children
var children = [];
//iterate through the children
target.parent.children.forEach(function(child) {
if (child.id != target.id) {
//add to teh child list if target id is not same
//so that the node target is removed.
children.push(child);
}
});
//set the target parent with new set of children sans the one which is removed
target.parent.children = children;
//redraw the parent since one of its children is removed
update(d.target.parent)
}
// 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;
});
addRightChild.on("click", function(d) {
event.stopPropagation();
$("#child-info").show();
$("#child-text").val("");
$("#btn-add-child").off('click');
$("#btn-add-child").click(function() {
var childname = $("#child-text").val();
if (typeof d.children === 'undefined') {
var newChild = [{
"name": childname,
"parent": "Son Of A",
}];
console.log(tree.nodes(newChild[0]));
var newnodes = tree.nodes(newChild);
d.children = newnodes[0];
console.log(d.children);
update(d);
} else {
var newChild = {
"name": childname,
"parent": "Son Of A",
};
console.log(d.children);
d.children.push(newChild);
console.log(d.children);
update(d);
}
$("#child-info").hide();
});
});;
}
// Toggle children on click.
function click(d) {
// console.log(d);
// if (d.children) {
// d._children = d.children;
// d.children = null;
// } else {
// d.children = d._children;
// d._children = null;
// }
// update(d);
}
}
function makeLeftTree() {
// ************** Generate the tree diagram *****************
var margin = {
top: 20,
right: 120,
bottom: 20,
left: 120
},
width = 1260 - 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("svg").append("g")
.attr("transform", "translate(-421,0)");
root = treeData2[0];
root.x0 = height / 2;
root.y0 = width;
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);
});
// 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", function(d) {
if (d.parent == "null") {
return "node leftparent" //since its root its parent is null
} else
return "node leftchild" //all nodes with parent will have this class
})
.attr("transform", function(d) {
return "translate(" + source.y0 + "," + source.x0 + ")";
})
.on("click", click);
nodeEnter.append("rect")
.attr("x", "-10")
.attr("y", "-15")
.attr("height", 30)
.attr("width", 100)
.attr("rx", 15)
.attr("ry", 15)
.style("fill", "#f1f1f1");
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);
var addLeftChild = nodeEnter.append("g");
addLeftChild.append("rect")
.attr("x", "-30")
.attr("y", "-10")
.attr("height", 20)
.attr("width", 20)
.attr("rx", 10)
.attr("ry", 10)
.style("stroke", "#444")
.style("stroke-width", "2")
.style("fill", "#ccc");
addLeftChild.append("line")
.attr("x1", -25)
.attr("y1", 1)
.attr("x2", -15)
.attr("y2", 1)
.attr("stroke", "#444")
.style("stroke-width", "2");
addLeftChild.append("line")
.attr("x1", -20)
.attr("y1", -4)
.attr("x2", -20)
.attr("y2", 6)
.attr("stroke", "#444")
.style("stroke-width", "2");
// 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
});
}).on("click", removelink);
function removelink(d) {
//this is the links target node which you want to remove
var target = d.target;
//make new set of children
var children = [];
//iterate through the children
target.parent.children.forEach(function(child) {
if (child.id != target.id) {
//add to teh child list if target id is not same
//so that the node target is removed.
children.push(child);
}
});
//set the target parent with new set of children sans the one which is removed
target.parent.children = children;
//redraw the parent since one of its children is removed
update(d.target.parent)
}
// 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;
});
addLeftChild.on("click", function(d) {
event.stopPropagation();
$("#child-info").show();
$("#child-text").val("");
$("#btn-add-child").off('click');
$("#btn-add-child").click(function() {
var childname = $("#child-text").val();
if (typeof d.children === 'undefined') {
var newChild = [{
"name": childname,
"parent": "Son Of A",
}];
console.log(tree.nodes(newChild[0]));
var newnodes = tree.nodes(newChild);
d.children = newnodes[0];
console.log(d.children);
update(d);
} else {
var newChild = {
"name": childname,
"parent": "Son Of A",
};
console.log(d.children);
d.children.push(newChild);
console.log(d.children);
update(d);
}
$("#child-info").hide();
});
});;
}
// Toggle children on click.
function click(d) {
// console.log(d);
// if (d.children) {
// d._children = d.children;
// d.children = null;
// } else {
// d.children = d._children;
// d._children = null;
// }
// update(d);
}
}
#child-info {
width: 100px;
height: 50px;
height: auto;
position: fixed;
padding: 10px;
display: none;
left: 40%;
}
#btn-add-child {} .control-bar {
min-height: 50px;
padding: 10px 0px;
background: #f1f1f1;
border-bottom: 1px solid #ccc;
box-shadow: 0 3px 2px -2px rgba(200, 200, 200, 0.2);
color: #666;
}
.asset-title {
padding: 15px;
float: left;
}
.control-buttons {
float: right;
padding: 10px;
}
.control-buttons button {
border: none;
border-radius: 0px;
background: #fff;
color: #666;
height: 30px;
width: 30px;
}
.node {
cursor: pointer;
}
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 3px;
}
.node text {
font: 12px sans-serif;
}
.link {
fill: none;
stroke: #85e0e0;
stroke-width: 2px;
}
.rightparent>rect {
display: none;
}
.leftparent>rect {
fill: #f1f1f1;
stroke: #ccc;
stroke-width: 2;
}
<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>
<div id="child-info" style="display:none">
<input type="text" id="child-text" placeholder="child name">
<button id="btn-add-child">add</button>
</div>
I'm trying to learn d3.js for the purpose of making a structure that looks like this. Where i can add and remove nodes dynamically , and i have been partially successful. ( with the help of lots of geeks here in stack overflow).
code snippet is as follows. The following has been achieved with two trees placed back to back. One tree - right oriented and other left oriented. The root node of both the trees are superposed.
The current working is as follows.
Click plus on the respective side to add a node , click on the link to remove the node and it's children. If you check the working sample code snippet it may work well initially.
But since the two trees are separate entity , once both sides becomes highly asymmetric the position of two root nodes will be different and two nodes are visible. ( one of them will be hidden but you can see the links starting from a different point - to see this issue try adding a few nodes on one side until it's root node position changes ). Something like this.
Now my question
Am I going the wrong way here ? Is there a way to directly convert a single json file into such a structure. I researched a lot and found this
wonderful answer on making family tree by Cyril. But I guess this case is different. Is there a way to make this structure directly ?
Or is there a way to move the nodes together based on movement of one node ?
Any guidance is highly appreciated.
To do this you will need to fix the root node.
This is how to fix the left/right roots.
Inside the function makeLeftTree.
oldlx = root.x0 = height / 2; //store the center x position
oldly = root.y0 = width; //store the center y position
Inside the function makeRightTree.
oldrx = root.x0 = height / 2; //store the center x position
oldry = root.y0 = width; //store the center y position
Then in the left node update you update the node position with the stored position.
var nodeUpdate = node.transition()
.duration(duration)
.attr("transform", function(d) {
if (d.parent =="null"){
d.y = oldly;
d.x = oldlx;
}
return "translate(" + d.y + "," + d.x + ")";
});
Same in the right node update you update the node position with the stored position.
var nodeUpdate = node.transition()
.duration(duration)
.attr("transform", function(d) {
if (d.parent =="null"){
d.y = oldry;
d.x = oldrx;
}
return "translate(" + d.y + "," + d.x + ")";
});
Working code here

Auto updating Tree issue

I have the following D3 js similar to
http://mbostock.github.io/d3/talk/20111018/tree.html
I want to have the tree structure auto update based on new json sent by the server.
The new json is sent every 5 seconds.
The issue is that I am not sure how to get rid of the old tree and just leave the updated tree. Currently it just draws a new tree image using d3 js under the most recent tree so very quickly there are tons of tree structures on the page. I would like to know how to remove the old tree image.
Any d3 or JavaScript input?
<style>
.node {
cursor: pointer;
}
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 1.5px;
}
.node text {
font: 10px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 1.5px;
}
</style>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var treeData2 = <%- JSON.stringify(treeJSON) %>;
drawTree();
function drawTree () {
treeData2.name = "broadcaster";
console.log("tree data = ", treeData2);
var margin = {top: 20, right: 120, bottom: 20, left: 120},
width = 960 - margin.right - margin.left,
height = 800 - margin.top - margin.bottom;
var i = 0,
duration = 750,
root;
var tree = d3.layout.tree()
.size([height, width]);
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.y, d.x]; });
svg = d3.select("body").append("svg")
.style("overflow", "scroll")
.attr("width", width + margin.right + margin.left)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.append("svg:g")
.attr("class","drawarea")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
root = treeData2;
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);
var inter = setInterval(function() {
socket.get('/channel/13/tree', function(updatedJSON) {
console.log("Updated Json = ", updatedJSON);
treeData2 = updatedJSON;
})
drawTree();
}, 5000);
d3.select(self.frameElement).style("height", "800px");
function update(source) {
// Compute the new tree layout.
var nodes = tree.nodes(root).reverse(),
links = tree.links(nodes);
// Normalize for fixed-depth.
nodes.forEach(function(d) { 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 ? -10 : 10; })
.attr("dy", ".35em")
.attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
.text(function(d) { return d.name; })
.style("fill-opacity", 1e-6);
// Transition nodes to their new position.
var nodeUpdate = node.transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; });
nodeUpdate.select("circle")
.attr("r", 4.5)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
nodeUpdate.select("text")
.style("fill-opacity", 1);
// Transition exiting nodes to the parent's new position.
var nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function(d) { return "translate(" + source.y + "," + source.x + ")"; })
.remove();
nodeExit.select("circle")
.attr("r", 1e-6);
nodeExit.select("text")
.style("fill-opacity", 1e-6);
// Update the links…
var link = svg.selectAll("path.link")
.data(links, function(d) { return d.target.id; });
// Enter any new links at the parent's previous position.
link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", function(d) {
var o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
});
// Transition links to their new position.
link.transition()
.duration(duration)
.attr("d", diagonal);
// Transition exiting nodes to the parent's new position.
link.exit().transition()
.duration(duration)
.attr("d", function(d) {
var o = {x: source.x, y: source.y};
return diagonal({source: o, target: o});
})
.remove();
// Stash the old positions for transition.
nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});
d3.select("svg")
.call(d3.behavior.zoom()
.scaleExtent([0.5, 5])
.on("zoom", zoom));
node
.exit()
.remove();
link
.exit()
.remove();
}
// 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);
}
// Allows for zoom and drag properties
function zoom() {
var scale = d3.event.scale,
translation = d3.event.translate,
tbound = -height * scale,
bbound = height * scale,
lbound = (-width + margin.right) * scale,
rbound = (width- margin.left) * scale;
// limit translation to thresholds
translation = [
Math.max(Math.min(translation[0], rbound), lbound),
Math.max(Math.min(translation[1], bbound), tbound)
];
d3.select(".drawarea")
.attr("transform", "translate(" + translation + ")" +
" scale(" + scale + ")");
}
}
</script>
To delete the old SVG, simply select and remove it:
d3.selectAll("svg").remove();

Categories

Resources