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.
Related
How can I wrap text inside each node making the node automatically resize, just as in css you would do with fit-content or display flex?
Here's the snippet, available at this link: https://codepen.io/boxxello/pen/XWYvRQO
or here:
css:
html, body {
margin: 0;
padding: 0;
background-color: rgb(140, 149, 226);
}
.node {
cursor: pointer;
}
.node circle {
}
.node-leaf {
}
.node text {
font: 10px sans-serif;
}
.link {
fill: none;
stroke: rgb(55, 68, 105);
stroke-width: 1px;
}
js:
var margin = {top: 20, right: 90, bottom: 30, left: 90},
width = 1300 - margin.left - margin.right,
height = 900 - margin.top - margin.bottom;
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 = 750,
root;
var treemap = d3.tree().size([height, width]);
root = d3.hierarchy(treeData, function (d) {
return d.children;
});
root.x0 = height / 2;
root.y0 = 0;
root.children.forEach(collapse);
update(root);
function collapse(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}
function update(source) {
var treeData = treemap(root);
var nodes = treeData.descendants(),
links = treeData.descendants().slice(1);
nodes.forEach(function (d) {
d.y = d.depth * 180;
});
var node = svg.selectAll("g.node").data(nodes, function (d) {
return d.id || (d.id = ++i);
});
var nodeEnter = node
.enter()
.append("g")
.attr("class", "node")
.attr("transform", function (d) {
return "translate(" + source.y0 + "," + source.x0 + ")";
})
.on("click", click);
nodeEnter
.attr("class", "node")
.attr("r", 1e-6)
.style("display", function (d) {
if (d.depth === 0) { //Is top root
return 'none';
}
});
nodeEnter
.append("rect")
.attr("rx", function (d) {
if (d.parent) return d.children || d._children ? 0 : 6;
return 10;
})
.attr("ry", function (d) {
if (d.parent) return d.children || d._children ? 0 : 6;
return 10;
})
.attr("stroke-width", function (d) {
return d.parent ? 1 : 0;
})
.attr("stroke", function (d) {
return d.children || d._children
? "rgb(3, 192, 220)"
: "rgb(38, 222, 176)";
})
.attr("stroke-dasharray", function (d) {
return d.children || d._children ? "0" : "2.2";
})
.attr("stroke-opacity", function (d) {
return d.children || d._children ? "1" : "0.6";
})
.attr("x", 0)
.attr("y", -10)
.attr("width", function (d) {
return d.parent ? 40 : 20;
})
.attr("height", 20)
.classed("node-leaf", true);
nodeEnter
.append("text")
.style("fill", function (d) {
if (d.parent) {
return d.children || d._children ? "#ffffff" : "rgb(38, 222, 176)";
}
return "rgb(39, 43, 77)";
})
.attr("dy", ".35em")
.attr("x", function (d) {
return d.parent ? 20 : 10;
})
.attr("text-anchor", function (d) {
return "middle";
})
.text(function (d) {
return d.data.name;
});
var nodeUpdate = nodeEnter.merge(node);
nodeUpdate
.transition()
.duration(duration)
.attr("transform", function (d) {
return "translate(" + d.y + "," + d.x + ")";
});
var nodeExit = node
.exit()
.transition()
.duration(duration)
.attr("transform", function (d) {
return "translate(" + source.y + "," + source.x + ")";
})
.remove();
nodeExit.select("rect").style("opacity", 1e-6);
nodeExit.select("rect").attr("stroke-opacity", 1e-6);
nodeExit.select("text").style("fill-opacity", 1e-6);
var link = svg.selectAll("path.link").data(links, function (d) {
return d.id;
});
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);
}).style("display", function (d) {
if (d.depth === 1) { //Is top link
return 'none';
}
})
var linkUpdate = linkEnter.merge(link);
linkUpdate
.transition()
.duration(duration)
.attr("d", function (d) {
return diagonal(d, d.parent);
});
var linkExit = link
.exit()
.transition()
.duration(duration)
.attr("d", function (d) {
var o = {x: source.x, y: source.y};
return diagonal(o, o);
})
.remove();
nodes.forEach(function (d) {
d.x0 = d.x;
d.y0 = d.y;
});
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;
}
function click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d);
}
}
The part where you could change the style property is at:
.attr("width", function (d) {
return d.parent ? 40 : 20;
})
.attr("height", 20)
.classed("node-leaf", true);
Or at least is where I've tried to deal with it. The current version I'm using of d3js is the 4.2.2, I actually used this version it fitted my needs (found the snippet online and there have been breaking changes in the 7.* which is the current version) not because I didn't want to upgrade it (if it's easier in the newer versions please let me know.
This is an expected output, as you can see the node basically fits all the text inside it (I left the parent nodes blank because they're not relevant in this case, but they would need to do the same thing, so applying a property to all the nodes would be great.
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>
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>
I added a d3.js library to project and i have few other libraries like jQuery, kendo ui, jQuery ui etc.
but collapse is not working on click of node of tree view. It is working in js fiddle but not in my application. is there are any conflicts?
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.node {
cursor: pointer;
}
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 1.5px;
}
.node text {
font: 10px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 1.5px;
}
</style>
<body>
<div id="lineageTrack"></div>
<script src="d3.js"></script>
<script>
var margin = {
top: 20,
right: 120,
bottom: 20,
left: 120
},
width = 960 - margin.right - margin.left,
height = 800 - margin.top - margin.bottom;
var root = {
"name": "flare",
"children": [{
"name": "analytics"
}, {
"name": "graph"
}]
};
var i = 0,
duration = 750,
rectW = 60,
rectH = 30;
var tree = d3.layout.tree().nodeSize([70, 40]);
var diagonal = d3.svg.diagonal()
.projection(function (d) {
return [d.x + rectW / 2, d.y + rectH / 2];
});
var svg = d3.select("#lineageTrack").append("svg").attr("width", 1000).attr("height", 1000)
.call(zm = d3.behavior.zoom().scaleExtent([1,3]).on("zoom", redraw)).append("g")
.attr("transform", "translate(" + 350 + "," + 20 + ")");
//necessary so that zoom knows where to zoom and unzoom from
zm.translate([350, 20]);
root.x0 = 0;
root.y0 = height / 2;
function collapse(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}
root.children.forEach(collapse);
update(root);
d3.select("#lineageTrack").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.x0 + "," + source.y0 + ")";
})
.on("click", click);
nodeEnter.append("rect")
.attr("width", rectW)
.attr("height", rectH)
.attr("stroke", "black")
.attr("stroke-width", 1)
.style("fill", function (d) {
return d._children ? "lightsteelblue" : "#fff";
});
nodeEnter.append("text")
.attr("x", rectW / 2)
.attr("y", rectH / 2)
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function (d) {
return d.name;
});
// Transition nodes to their new position.
var nodeUpdate = node.transition()
.duration(duration)
.attr("transform", function (d) {
return "translate(" + d.x + "," + d.y + ")";
});
nodeUpdate.select("rect")
.attr("width", rectW)
.attr("height", rectH)
.attr("stroke", "black")
.attr("stroke-width", 1)
.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.x + "," + source.y + ")";
})
.remove();
nodeExit.select("rect")
.attr("width", rectW)
.attr("height", rectH)
//.attr("width", bbox.getBBox().width)""
//.attr("height", bbox.getBBox().height)
.attr("stroke", "black")
.attr("stroke-width", 1);
nodeExit.select("text");
// 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("x", rectW / 2)
.attr("y", rectH / 2)
.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);
}
//Redraw for zoom
function redraw() {
//console.log("here", d3.event.translate, d3.event.scale);
svg.attr("transform",
"translate(" + d3.event.translate + ")"
+ " scale(" + d3.event.scale + ")");
}
</script>
</body>
</html>
see the elements
Your file may conflict with jquery.min.js or with other libraries and so that it may be in conflict. So you need to keep the d3.js file just above to all library files. It will work fine.
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();