d3 treemap dynamic data not adjusting cell width/height - d3.js

I have a treemap (simple) to which I want to add a new element (see DS0 and DS1 in the code below). I don't want to re-create the whole treemap, instead I want to "update" the data.
Sticky is false
update section adjusts the g transform (OK)
update section adjusts the contained rect width/height (not OK)
with devmode off (chrome) the rects width/heights are not being updated (looks like the d.x and d.y values are the old values - can be seen with the cosnole.log statements)
with devmode on (chrome) the 'debugger' statements kick in, and if I step through, the some width values update OK.
I can't see why this is not updating properly, but I can make a few observations. It appears that the data binding to the <g>, <rect> and <text> elements is not being adjusted when new data comes in. certainly the <text> data remains 'old'.
Perhaps the only intended way to do this is to re-create the whole SVG again?
diagrams
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Test Dynamic Treemap</title>
<style>
rect { fill: none; stroke: #fff;}
text { font: 10px sans-serif;}
</style>
<body>
<input type="button" id="add" value="add">
<input type="button" id="remove" value="remove">
<br>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 500,
color = d3.scale.category20c();
var treemap = d3.layout.treemap()
.padding([15,5,5,5])
.size([width, height])
.sticky(false)
.value(function(d) { return 5; });
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(-.5,-.5)");
var DS0 =
{'name': 'data', 'children': [
{'name':'A', 'children':[
{'name':'A01' },
{'name':'A02'}
]},
]}
var DS1 =
{'name': 'data', 'children': [
{'name':'A', 'children':[
{'name':'A01' },
{'name':'A02'},
{'name':'A03'}
]},
]}
d3.select('#add').on('click',function() {withData(DS1)})
d3.select('#remove').on('click',function() {withData(DS0)})
withData(DS0);
function withData(json){
var cell = svg.data([json]).selectAll("g")
.data(treemap.nodes)
// BEGIN UPDATE SECTION
var updates = cell.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
// adjust the parameters of the updated objects
updates.selectAll("rect") // These only seem to use 'new' data when stepped through in debugger
// ======================================================================
.attr("width", function(d) { debugger; console.log(d.name + ' setting width to ' + d.dx); return d.dx; })
.attr("height", function(d) { debugger; console.log(d.name + ' setting height to ' + d.dy); return d.dy; })
.style("fill", function(d) { return d.children ? color(d.name) : "yellow"; })
// END UPDATE SECTION
// BEGIN ENTER SECTION (ADDS)
var adds = cell.enter().append("g")
.attr("class", function(d) {return "cell " + d.name})
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
adds.append("rect")
.attr("width", function(d) { return d.dx; })
.attr("height", function(d) { return d.dy; })
.style("fill", function(d) { return d.children ? color(d.name) : null; })
adds.append("text")
.attr("x", function(d) { return d.dx / 2; })
.attr("y", function(d) { return 5; })
.attr("dy", ".35em")
.attr("text-anchor", "top")
.text(function(d) { return d.children ? d.name : d.name; });
// END ENTER SECTION (ADDS)
// BEGIN UPDATE AND ENTER SECTION (Updates And ADDS)
//var updatesAndAdds = cell.attr("transform", function(d) { console.log("UpdateAndUpdate:" + d.name); return "translate(" + d.x + "," + d.y + ")"; });
// END UPDATE AND ENTER SECTION (Updates And ADDS)
// BEGIN EXIT SECTION (Updates And ADDS)
var rems = cell.exit().remove();
// END EXIT SECTION (Updates And ADDS)
};
</script>

This code:
var adds = cell.enter().append("g")
...
adds.append("text")
.attr("x", function(d) { return d.dx / 2; })
.attr("y", function(d) { return 5; })
Means you are only handling the enter selection for the text elements. The code above it:
updates.selectAll("rect")
Is handling the update selection for the rects (and you need something like it for the text elements).
Let's take a step back and try to clean this up a bit (untested code):
////////////
// this is the entire selection
/////////////
var cell = svg.data([json]).selectAll("g")
.data(treemap.nodes);
/////////////
// remove is easy, get it out of the way
/////////////
cell.exit().remove();
/////////////
// do all the entering first
////////////
// enter the gs
var eCell = cell.enter().append("g")
.attr("class", function(d) {return "cell " + d.name});
// and rect for that g
eCell.append("rect")
.style("fill", function(d) { return d.children ? color(d.name) : null; });
// and a text for that g
eCell.append("text")
.attr("y", function(d) { return 5; })
.attr("dy", ".35em")
.attr("text-anchor", "top");
/////////////
// now do all the updating, this is enter + update
////////////
// move the g
cell.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
// resize/move the rect
cell.select("rect")
.attr("width", function(d) { debugger; console.log(d.name + ' setting width to ' + d.dx); return d.dx; })
.attr("height", function(d) { debugger; console.log(d.name + ' setting height to ' + d.dy); return d.dy; });
// move the text and update value
cell.select("text")
.attr("x", function(d) { return d.dx / 2; })
.text(function(d) { return d.children ? d.name : d.name; });

Related

Adding Labels to Links in Tree D3.js

Hi i need to add Labels for Tree D3.js on the links without a rectangle box on mouseover. And on the rectangle I need a tooltip displaying text inside a rectangle on mouse over and also dispaly the same toolTip when mouseover on link.
Below is the d3 js of version4 I am using. Please help me with this.
I want to achieve an img like this.
let treeData,
path;
treeData =JSON.parse(this.traceableData);
const treeHeight=(treeData.children.length*50);
this.imgHeight=treeHeight;
let children=treeData.children;
let imghtIncrement=0;
for(let i=0;i<children.length;i++)
{
if(children[i].name.length>0)
{
imghtIncrement=imghtIncrement+40;
}
}
let rectNode = {
width: 120,
height: 17,
textMargin: 5
};
// Set the dimensions and margins of the diagram
let margin = {top: 20, right: 120, bottom: 30, left: 160},
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
let svg = d3.select(this.template.querySelector('svg.d3'))
.attr("width", width + margin.right + margin.left+200)
.attr("height", this.imgHeight+imghtIncrement+100)
.append("g")
.attr("transform", "translate("
+ margin.left + "," + margin.top + ")");
let i = 0,
duration = 750,
root;
// declares a tree layout and assigns the size
let treemap = d3.tree().size([this.imgHeight+imghtIncrement, width+200]);
// Assigns parent, children, height, depth
root = d3.hierarchy(treeData, function(d) { return d.children; });
root.x0 = height / 2;
root.y0 = 0;
//Collapse the Node and all its Children
function collapse(d) {
if (d.children) {
d.all_children = d.children;
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
d.hidden = true;
}
}
root.hidden = false;
update(root);
d3.select(self.frameElement).style("height", "800px");
function update(source) {
let nodeHeight=15;
// Assigns the x and y position for the nodes
treeData = treemap(root);
// Compute the new tree layout.
let nodes = treeData.descendants(),
links = treeData.descendants().slice(1);
// Normalize for fixed-depth.
nodes.forEach(function(d){ d.y = d.depth * 200});
// ****************** Nodes section ***************************
// Update the nodes...
let 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.
let nodeEnter = node.enter().append('g')
.attr('class', 'node')
.attr("transform", function(d) {
console.log(d);
return "translate(" + source.y0 + "," + source.x0 + ")";
})
.on("click", click)
.on("mouseover", function(d) {
let g = d3.select(this); // The node
// The class is used to remove the additional text later
g.append('text')
.classed('info', true)
.attr('x', -80)
.attr('y', -30)
.text(d.data.objectType);
})
.on("mouseout", function() {
// Remove the info text on mouse out.
d3.select(this).select('text.info').remove()
});
// Add Circle for the nodes
nodeEnter.append('circle')
.attr('class', 'node')
.attr('r', 1e-6)
.style("fill", function(d) {
return d.children ? "lightsteelblue" : "#fff";
});
let rectGrpEnter = nodeEnter.append('g')
.attr('class', 'node-rect-text-grp');
rectGrpEnter.append('rect')
.attr('rx', 6)
.attr('ry', 6)
.attr('x',-120)
.attr('y',-20)
.attr('width', rectNode.width)
.attr('height', function(d){
let rectVariedHeight;
if(Math.ceil(d.data.name.length/nodeHeight<1.01)){
rectVariedHeight=40;
}
else
{
rectVariedHeight=rectNode.height*Math.ceil(d.data.name.length/nodeHeight);
}
return rectVariedHeight; })
.attr('fill', "white")
.style("stroke-width", 1)
.style("stroke", "black")
.attr('class', 'node-rect');
rectGrpEnter.append("text")
.attr("dx", function(d) {
let x=0;
if(Math.ceil(d.data.name.length<11)){
x=-160;
}
else
{
x=-125;
}
return d.children ? x : -220;
})
.attr("dy", "-5")
.attr('cursor', 'pointer')
.on("mouseover", function() {d3.select(this).style("fill", "#0000FF");})
.on("mouseout", function() {d3.select(this).style("fill", "black");})
.on("click", function(d) { window.open(d.data.url);})
.each(function(d) {
let noofTextParts;
if(d.children){
noofTextParts=Math.ceil(d.data.name.length/nodeHeight);
}
else{
noofTextParts=Math.ceil(d.data.name.length/nodeHeight);
}
// eslint-disable-next-line no-shadow
for(let i=0;i<noofTextParts;i++)
{
d3.select(this).append("tspan")
.attr("dy", i ? "1.2em" : -5)
// eslint-disable-next-line no-unused-vars
.attr("x", function(d2) {
let len;
if(i!==0)
{
if(d2.children)
{
len= -10;
}
else
{
len=-115;
}
}
else
{
len= 105;
}
return len;
}
)
.attr("class", "tspan" + i)
.style("text-anchor", function(d3) { return d3.children ? "end" : "start"; })
.text(function(d1) {
let nodeName;
if(d1.children)
{
nodeName=d1.data.name.substring(i*nodeHeight,(i+1)*nodeHeight);}
else
{
nodeName= d1.data.name.substring(i*nodeHeight,(i+1)*nodeHeight);
}
return nodeName;
});
}
});
// UPDATE
let 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 + ")";
});
let circleRadius = 0;
// Update the node attributes and style
nodeUpdate.select('circle.node')
.attr('r', circleRadius)
.style("fill", function(d) {
return d._children ? "lightsteelblue" : "#fff";
})
.attr('cursor', 'pointer');
// Remove any exiting nodes
let nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", function(d) {
console.log(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...
let link = svg.selectAll('path.link')
.data(links, function(d) { return d.id; });
// Enter any new links at the parent's previous position.
let linkEnter = link.enter().insert('path', "g")
.attr("class", "link")
.attr('d', function(d){
console.log(d);
let o = {x: source.x0, y: source.y0}
return diagonal(o, o)
});
// UPDATE
let 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
let linkExit = link.exit().transition()
.duration(duration)
.attr('d', function(d) {
console.log(d);
let o = {x: source.x, y: source.y}
return diagonal(o, o)
})
.remove();
console.log(linkExit);
// 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- (rectNode.width + circleRadius) } ${s.x}
C ${(s.y- (rectNode.width + circleRadius) + d.y ) / 2} ${s.x},
${(s.y- (rectNode.width + circleRadius) + d.y ) / 2} ${d.x},
${d.y } ${d.x}`
return path
}
}
if(root.hasOwnProperty("children"))
//Only children will be collpased
{
root.children.forEach(collapse);
}
// To collapse all to root element
collapse(root);
//Changes added for collapsing ends
update(root);
// Toggle children on click.
function click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
if (d._children) {
d._children.forEach(function(n) { n.hidden = true; });
if (d.parent) {
d.parent.children = d.parent.all_children;
d.parent.children.forEach(function(n) {
n.hidden = false;
});
}
}
} else {
d.children = d._children;
d._children = null;
if (d.children) {
d.children.forEach(function(n) { n.hidden = false; });
if (d.parent) {
d.parent.children = [d,];
d.parent.children.filter(function(n) { return n !== d; }).forEach(function(n) {
n.hidden = true;
});
}
}
}
update(d);
}
I have added labels to the links.
Hope it helps you.
<!DOCTYPE html>
<meta charset="UTF-8">
<style>
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 3px;
}
.node text {
font: 12px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 2px;
}
.link path {
fill: none;
stroke: #ccc;
stroke-width: 2px;
}
.link text {
font: 12px sans-serif;
stroke: #333;
stroke-width: 1;
}
</style>
<body>
<!-- load the d3.js library -->
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var treeData =
{
"name": "Top Level",
"linkname": "null",
"children": [
{
"name": "Level 2: A",
"linkname": "Link_1",
"children": [
{ "name": "Son of A", "linkname": "Link_2.1" },
{ "name": "Daughter of A", "linkname": "Link_2.2" }
]
},
{ "name": "Level 2: B", "linkname": "Link_3", }
]
};
// Set the dimensions and margins of the diagram
var margin = { top: 20, right: 90, bottom: 30, left: 90 },
width = 960 - margin.left - margin.right,
height = 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("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;
// declares a tree layout and assigns the size
var treemap = d3.tree().size([height, width]);
// Assigns parent, children, height, depth
root = d3.hierarchy(treeData, function (d) { return d.children; });
root.x0 = height / 2;
root.y0 = 0;
// Collapse after the second level
root.children.forEach(collapse);
update(root);
// Collapse the node and all it's children
function collapse(d) {
if (d.children) {
d._children = d.children
d._children.forEach(collapse)
d.children = null
}
}
function update(source) {
// Assigns the x and y position for the nodes
var treeData = treemap(root);
// Compute the new tree layout.
var nodes = treeData.descendants(),
links = treeData.descendants().slice(1);
// Normalize for fixed-depth.
nodes.forEach(function (d) {
d.y = d.depth * 180
});
// ****************** Nodes section ***************************
// Update the nodes...
var node = svg.selectAll('g.node')
.data(nodes, function (d) {
return d.id || (d.id = ++i);
});
// Enter any new modes at the parent's previous position.
var nodeEnter = node.enter().append('g')
.attr('class', 'node')
.attr("transform", function (d) {
return "translate(" + source.y0 + "," + source.x0 + ")";
})
.on('click', click);
// Add Circle for the nodes
nodeEnter.filter(function (d) {
return (!d.data.type || d.data.type !== 'data');
}).append('circle')
.attr('class', 'node')
.attr('r', 1e-6)
.style("fill", function (d) {
return d._children ? "lightsteelblue" : "#fff";
});
nodeEnter.filter(function (d) {
return (d.data.type && d.data.type === 'data');
}).append('rect')
.attr('class', 'node')
.attr('width', 20)
.attr('height', 20)
.attr('y', -10)
.attr('x', -10)
.style("fill", function (d) {
return d._children ? "lightsteelblue" : "#fff";
});
// Add labels for the nodes
nodeEnter.append('text')
.attr("dy", "2em")
.attr("x", function (d) {
return d.children || d._children ? 13 : 13;
})
.attr("text-anchor", function (d) {
return d.children || d._children ? "start" : "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.y + "," + d.x + ")";
});
// 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('g.link')
.data(links, function (d) {
return d.id;
});
// Enter any new links at the parent's previous position.
var linkEnter = link.enter().insert('g', 'g')
.attr("class", "link");
linkEnter.append('text')
.attr("class","linkLabels")
.text(function (d, i) {
if (d.parent && d.parent.children.length > 1) {
if (!d.parent.index) d.parent.index = 0;
return d.data.linkname;
}
})
.attr("opacity",0)
.attr('dy', "-1em");
linkEnter.append('path')
.attr('d', function (d) {
var o = {
x: source.x0,
y: source.y0
}
return diagonal(o, o)
})
.on("mouseover", function(){
d3.select(this.parentNode).select("text").attr("opacity",1);
})
.on("mouseleave", function(){
d3.select(this.parentNode).select("text").attr("opacity",0);
})
// UPDATE
var linkUpdate = linkEnter.merge(link);
// Transition back to the parent element position
linkUpdate.select('path').transition()
.duration(duration)
.attr('d', function (d) {
return diagonal(d, d.parent)
});
linkUpdate.select('text').transition()
.duration(duration)
.attr('transform', function (d) {
if (d.parent) {
return 'translate(' + ((d.parent.y + d.y) / 2) + ',' + ((d.parent.x + d.x) / 2) + ')'
}
})
// Remove any exiting links
link.exit().each(function (d) {
d.parent.index = 0;
})
var linkExit = link.exit()
.transition()
.duration(duration);
linkExit.select('path')
.attr('d', function (d) {
var o = {
x: source.x,
y: source.y
}
return diagonal(o, o)
})
linkExit.select('text')
.style('opacity', 0);
linkExit.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>

find specific nodes in d3js tree

I am trying to find specific nodes on the tree layout. I found this example on plunkr:
function collapse(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(function(d1){d1.parent = d; collapse(d1);});
d.children = null;
}}
function find(d, name) {
if (d.name == name){
while(d.parent){
d = d.parent;
click(d)
}
return;
}
if (d.children) {
d.children.forEach(function(d){find(d, name)});
} else if(d._children){
d._children.forEach(function(d){find(d, name)});
}}
[root].forEach(collapse);
var name = "layout"
find (root, name)
update(root);
http://plnkr.co/edit/Ce5Ub8PWXblSMcrYlkHa?p=preview which finds a specif node given a name. I adopted it to find a node given an ID.I have two problems with the implementation:
1- The code generates an error in the console "Error: attribute transform: Expected number, "translate(undefined,undefi…". Which I think is due to the x and y coordinates becoming null, but I cannot identify the exact condition. This error appears in the original example as well.
2- If I call the find routine once (by clicking the find button which calls find_name() and commenting out the second call to the find function) , it works, however if I call it more than once (by un-commenting and enabling the second call to find), the tree collapses to the root node.
Any help in understanding this behavior is much appreciated.
<!-- load the d3.js library -->
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
// ************** Generate the tree diagram *****************
var data =[{"sid":"1","parent":"null","name_ar":"Hashim"},{"sid":"2","parent":"1","name_ar":"wahb"},{"sid":"3","parent":"1","name_ar":"Abdulmuttaleb"},{"sid":"4","parent":"2","name_ar":"Amina"},{"sid":"5","parent":"3","name_ar":"Abutaleb"},{"sid":"6","parent":"3","name_ar":"Abdulla"},{"sid":"7","parent":"3","name_ar":"Abbas"},{"sid":"8","parent":"3","name_ar":"Hamza"},{"sid":"9","parent":"6","name_ar":"Mohammed (Prophet)"},{"sid":"10","parent":"9","name_ar":"Alqassim"},{"sid":"11","parent":"9","name_ar":"Um Kalthoum"},{"sid":"12","parent":"9","name_ar":"Zainab"},{"sid":"13","parent":"9","name_ar":"Ruqaya"},{"sid":"14","parent":"9","name_ar":"Fatima"},{"sid":"15","parent":"9","name_ar":"Ibrahim"},{"sid":"16","parent":"9","name_ar":"Abdulla"},{"sid":"17","parent":"9","name_ar":"Muhsen"},{"sid":"18","parent":"5","name_ar":"Ali"},{"sid":"19","parent":"18","name_ar":"Hassan"},{"sid":"20","parent":"18","name_ar":"Hussain"},{"sid":"21","parent":"20","name_ar":"Ali Zain Alabbideen"},{"sid":"22","parent":"21","name_ar":"Mohammed Baqer"},{"sid":"23","parent":"22","name_ar":"Jafar Sadeq"},{"sid":"24","parent":"23","name_ar":"Mousa Kadim"},{"sid":"25","parent":"24","name_ar":"Ali AlAreed"},{"sid":"26","parent":"24","name_ar":"Ibrahim Murtada"},{"sid":"27","parent":"26","name_ar":"Mousa (the second)"},{"sid":"28","parent":"27","name_ar":"Ahmed"},{"sid":"29","parent":"28","name_ar":"Hussain"},{"sid":"30","parent":"29","name_ar":"Abu Alqassim Mohammed"},{"sid":"31","parent":"30","name_ar":"Najm Aldeen Mahdi"}];
//------------------
//the find function is global
function collapse(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(function(d1){d1.parent = d; collapse(d1);});
d.children = null;
}
}
function find(d, sid) {
if (d.sid == sid){
while(d.parent){
d = d.parent;
click(d)
}
return;
}
if (d.children) {
d.children.forEach(function(d){find(d, sid)});
} else if(d._children){
d._children.forEach(function(d){find(d, sid)});
}
}
function find_name(){
[root].forEach(collapse); //iterate each node and collapse
find(root,25);
find(root,31);
update(root);
}
//------------------
var margin = {top: 25, right: 120, bottom: 20, left: 120},
width = 10000 - margin.right - margin.left,
height = 5000 - margin.top - margin.bottom;
var i = 0,
duration = 750,
rectW = 100,
rectH = 30,
root;
var enteredId = 7402;
//zoom functionality
var zoom = d3.behavior.zoom()
.scaleExtent([1, 10])
.on("zoom", zoomed);
var tree = d3.layout.tree()
.nodeSize([110, 50]);
var diagonal = d3.svg.diagonal()
.projection(function (d) { return [d.x + rectW / 2, d.y + rectH / 2]; });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.right + margin.left)
.attr("height", height + margin.top + margin.bottom)
.call(zoom)
.on("wheel.zoom", null) //disable zooming on mouse wheel scroll
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//create a name-based map for the nodes
//which starts with an empty object and iterates over the data array, adding an entry for each node
//for the flat array
var dataMap = data.reduce(function(map, node) {
map[node.sid] = node;
return map;
}, {});
//iteratively add each child to its parents, or to the root array if no parent is found
//for the flat array
var treeData = [];
data.forEach(function(node) {
// add to parent
var parent = dataMap[node.parent];
if (parent) {
// create child array if it doesn't exist
(parent.children || (parent.children = []))
// add node to child array
.push(node);
} else {
// parent is null or missing
treeData.push(node);
}
});
root = treeData[0];
root.x0 = height / 2;
root.y0 = 0;
//------------------------------------------------------
var nodes = tree.nodes(root);
function collapseLevel(d) {
if (d.children && d.depth > 23) {
d._children = d.children;
d._children.forEach(collapseLevel);
d.children = null;
} else if (d.children) {
d.children.forEach(collapseLevel);
}
}
root.children.forEach(collapseLevel);//iterate each node and collapse excluding node zero
//------------------------------------------------------
update(root);
d3.select(self.frameElement).style("height", "500px");
function zoomed() {
svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
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.
//vertical tree by swaping y0 and x0
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + source.x0 + "," + source.y0 + ")"; })
.on("click", click)
.on("mouseover", function(d) {
var g = d3.select(this); // The node
// The class is used to remove the additional text later
var info = g.append('text')
.classed('info', true)
.attr('x', 20)
.attr('y', 10)
.text(function(d) { return d.name_ar + " " + d.sid }); // need to put good background for tooltip
})
.on("mouseout", function() {
// Remove the info text on mouse out.
d3.select(this).select('text.info').remove()
});
;
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_ar; })
.style("fill-opacity", 1);
//vertical
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.
//vertical
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("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("d", function(d) {
var o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
});
// Transition links to their new position.
link.transition()
.duration(duration)
.attr("d", diagonal);
// Transition exiting nodes to the parent's new position.
link.exit().transition()
.duration(duration)
.attr("d", function(d) {
var o = {x: source.x, y: source.y};
return diagonal({source: o, target: o});
})
.remove();
// Stash the old positions for transition.
nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});
}
// Toggle children on click.
function click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d);
}
//-------------------------------------
</script>
.node {
cursor: pointer;
}
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 3px;
}
.node text {
font: 14px 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>
<header>
<button onclick="find_name()">find</button>
</header>
</head>
The reason for the error in the first question "The code generates an error in the console "Error: attribute transform: Expected number, "translate(undefined,undefi" is due to the SID being character. I converted it to integer and no error is generated.

Collapse d3js tree to a specified depth

I'm new to d3js and javascript in general. I am trying to create a tree of more than 8000 nodes, and used the basic tree examples available and modified to display vertically.
Example data is hard coded, however, on my local server, I read the data from an external JSON file.
I would like to be able to specify the depth level to start with (collapse all node deeper than 2) and allow the user to further expand or collapse nodes.
I tried modifying the "collapse" function to check for the depth level, however, the logic is not correct.
Appreciate any help in this regard.
<!-- load the d3.js library -->
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
//------------------
var data =[{"sid":"1","parent":"null","name_ar":"Hashim"},{"sid":"2","parent":"1","name_ar":"wahb"},{"sid":"3","parent":"1","name_ar":"Abdulmuttaleb"},{"sid":"4","parent":"2","name_ar":"Amina"},{"sid":"5","parent":"3","name_ar":"Abutaleb"},{"sid":"6","parent":"3","name_ar":"Abdulla"},{"sid":"7","parent":"3","name_ar":"Abbas"},{"sid":"8","parent":"3","name_ar":"Hamza"},{"sid":"9","parent":"6","name_ar":"Mohammed (Prophet)"},{"sid":"10","parent":"9","name_ar":"Alqassim"},{"sid":"11","parent":"9","name_ar":"Um Kalthoum"},{"sid":"12","parent":"9","name_ar":"Zainab"},{"sid":"13","parent":"9","name_ar":"Ruqaya"},{"sid":"14","parent":"9","name_ar":"Fatima"},{"sid":"15","parent":"9","name_ar":"Ibrahim"},{"sid":"16","parent":"9","name_ar":"Abdulla"},{"sid":"17","parent":"9","name_ar":"Muhsen"},{"sid":"18","parent":"5","name_ar":"Ali"},{"sid":"19","parent":"18","name_ar":"Hassan"},{"sid":"20","parent":"18","name_ar":"Hussain"},{"sid":"21","parent":"20","name_ar":"Ali Zain Alabbideen"},{"sid":"22","parent":"21","name_ar":"Mohammed Baqer"},{"sid":"23","parent":"22","name_ar":"Jafar Sadeq"},{"sid":"24","parent":"23","name_ar":"Mousa Kadim"},{"sid":"25","parent":"24","name_ar":"Ali AlAreed"},{"sid":"26","parent":"24","name_ar":"Ibrahim Murtada"},{"sid":"27","parent":"26","name_ar":"Mousa (the second)"},{"sid":"28","parent":"27","name_ar":"Ahmed"},{"sid":"29","parent":"28","name_ar":"Hussain"},{"sid":"30","parent":"29","name_ar":"Abu Alqassim Mohammed"},{"sid":"31","parent":"30","name_ar":"Najm Aldeen Mahdi"}];
//need to find a way to dynamically set the "Width" as the tree is very deep
var margin = {top: 25, right: 120, bottom: 20, left: 120},
width = 10000 - margin.right - margin.left,
height = 5000 - margin.top - margin.bottom;
var i = 0,
duration = 750,
rectW = 100,
rectH = 30,
root;
// zoom functionality
var zoom = d3.behavior.zoom()
.scaleExtent([1, 10])
.on("zoom", zoomed);
var tree = d3.layout.tree()
.nodeSize([110, 50]); // increased to 110 to avoid node overlap
var diagonal = d3.svg.diagonal()
.projection(function (d) { return [d.x + rectW / 2, d.y + rectH / 2]; });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.right + margin.left)
.attr("height", height + margin.top + margin.bottom)
.call(zoom) // added to call to zoom to enable zooming; it works :}
.on("wheel.zoom", null) // disable zooming on mouse wheel scroll
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//create a name-based map for the nodes
//which starts with an empty object and iterates over the data array, adding an entry for each node
//for the flat array
var dataMap = data.reduce(function(map, node) {
map[node.sid] = node;
return map;
}, {});
//iteratively add each child to its parents, or to the root array if no parent is found
//for the flat array
var treeData = [];
data.forEach(function(node) {
// add to parent
var parent = dataMap[node.parent];
if (parent) {
// create child array if it doesn't exist
(parent.children || (parent.children = []))
// add node to child array
.push(node);
} else {
// parent is null or missing
treeData.push(node);
}
});
root = treeData[0];
root.x0 = height / 2; // should this be width/2 for the vertical?
root.y0 = 0;
//testing using depth to open at a specified level
var nodes = tree.nodes(root);
function collapseLevel(d) {
console.log("sid "+d.sid+" depth "+d.depth);
if (d.children && d.depth > 2) { // doesn't work as it exits at parent depth
d._children = d.children;
d._children.forEach(collapseLevel);
d.children = null;
}
}
root.children.forEach(collapseLevel);//iterate each node and collapse excluding node zero
update(root);
d3.select(self.frameElement).style("height", "500px");
//zoom (drag the tree around !)
function zoomed() {
svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
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.
//vertical tree by swaping y0 and x0
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + source.x0 + "," + source.y0 + ")"; })
.on("click", click)
.on("mouseover", function(d) {
var g = d3.select(this); // The node
var info = g.append('text')
.classed('info', true)
.attr('x', 20)
.attr('y', 10)
.text(function(d) { return d.name_ar + " " + d.sid });
})
.on("mouseout", function() {
// Remove the info text on mouse out.
d3.select(this).select('text.info').remove()
});
;
//rectagular nodes
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_ar; })
.style("fill-opacity", 1);
// Transition nodes to their new position.
//vertical
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.
//vertical
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("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("d", function(d) {
var o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
});
// Transition links to their new position.
link.transition()
.duration(duration)
.attr("d", diagonal);
// Transition exiting nodes to the parent's new position.
link.exit().transition()
.duration(duration)
.attr("d", function(d) {
var o = {x: source.x, y: source.y};
return diagonal({source: o, target: o});
})
.remove();
// Stash the old positions for transition.
nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});
}
// Toggle children on click.
function click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d);
}
</script>
<style>
.node {
cursor: pointer;
}
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 3px;
}
.node text {
font: 18px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 2px;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Tree Example</title>
</head>
You have to provide an else if condition, in case the if condition is falsy:
function collapseLevel(d) {
if (d.children && d.depth > 1) {
d._children = d.children;
d._children.forEach(collapseLevel);
d.children = null;
} else if (d.children) {
d.children.forEach(collapseLevel);
}
}
Here is your code with that change:
var data =[{"sid":"1","parent":"null","name_ar":"Hashim"},{"sid":"2","parent":"1","name_ar":"wahb"},{"sid":"3","parent":"1","name_ar":"Abdulmuttaleb"},{"sid":"4","parent":"2","name_ar":"Amina"},{"sid":"5","parent":"3","name_ar":"Abutaleb"},{"sid":"6","parent":"3","name_ar":"Abdulla"},{"sid":"7","parent":"3","name_ar":"Abbas"},{"sid":"8","parent":"3","name_ar":"Hamza"},{"sid":"9","parent":"6","name_ar":"Mohammed (Prophet)"},{"sid":"10","parent":"9","name_ar":"Alqassim"},{"sid":"11","parent":"9","name_ar":"Um Kalthoum"},{"sid":"12","parent":"9","name_ar":"Zainab"},{"sid":"13","parent":"9","name_ar":"Ruqaya"},{"sid":"14","parent":"9","name_ar":"Fatima"},{"sid":"15","parent":"9","name_ar":"Ibrahim"},{"sid":"16","parent":"9","name_ar":"Abdulla"},{"sid":"17","parent":"9","name_ar":"Muhsen"},{"sid":"18","parent":"5","name_ar":"Ali"},{"sid":"19","parent":"18","name_ar":"Hassan"},{"sid":"20","parent":"18","name_ar":"Hussain"},{"sid":"21","parent":"20","name_ar":"Ali Zain Alabbideen"},{"sid":"22","parent":"21","name_ar":"Mohammed Baqer"},{"sid":"23","parent":"22","name_ar":"Jafar Sadeq"},{"sid":"24","parent":"23","name_ar":"Mousa Kadim"},{"sid":"25","parent":"24","name_ar":"Ali AlAreed"},{"sid":"26","parent":"24","name_ar":"Ibrahim Murtada"},{"sid":"27","parent":"26","name_ar":"Mousa (the second)"},{"sid":"28","parent":"27","name_ar":"Ahmed"},{"sid":"29","parent":"28","name_ar":"Hussain"},{"sid":"30","parent":"29","name_ar":"Abu Alqassim Mohammed"},{"sid":"31","parent":"30","name_ar":"Najm Aldeen Mahdi"}];
//need to find a way to dynamically set the "Width" as the tree is very deep
var margin = {top: 25, right: 120, bottom: 20, left: 120},
width = 10000 - margin.right - margin.left,
height = 5000 - margin.top - margin.bottom;
var i = 0,
duration = 750,
rectW = 100,
rectH = 30,
root;
// zoom functionality
var zoom = d3.behavior.zoom()
.scaleExtent([1, 10])
.on("zoom", zoomed);
var tree = d3.layout.tree()
.nodeSize([110, 50]); // increased to 110 to avoid node overlap
var diagonal = d3.svg.diagonal()
.projection(function (d) { return [d.x + rectW / 2, d.y + rectH / 2]; });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.right + margin.left)
.attr("height", height + margin.top + margin.bottom)
.call(zoom) // added to call to zoom to enable zooming; it works :}
.on("wheel.zoom", null) // disable zooming on mouse wheel scroll
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//create a name-based map for the nodes
//which starts with an empty object and iterates over the data array, adding an entry for each node
//for the flat array
var dataMap = data.reduce(function(map, node) {
map[node.sid] = node;
return map;
}, {});
//iteratively add each child to its parents, or to the root array if no parent is found
//for the flat array
var treeData = [];
data.forEach(function(node) {
// add to parent
var parent = dataMap[node.parent];
if (parent) {
// create child array if it doesn't exist
(parent.children || (parent.children = []))
// add node to child array
.push(node);
} else {
// parent is null or missing
treeData.push(node);
}
});
root = treeData[0];
root.x0 = height / 2; // should this be width/2 for the vertical?
root.y0 = 0;
//testing using depth to open at a specified level
var nodes = tree.nodes(root);
function collapseLevel(d) {
if (d.children && d.depth > 1) {
d._children = d.children;
d._children.forEach(collapseLevel);
d.children = null;
} else if (d.children){
d.children.forEach(collapseLevel);
}
}
root.children.forEach(collapseLevel);//iterate each node and collapse excluding node zero
update(root);
d3.select(self.frameElement).style("height", "500px");
//zoom (drag the tree around !)
function zoomed() {
svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
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.
//vertical tree by swaping y0 and x0
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + source.x0 + "," + source.y0 + ")"; })
.on("click", click)
.on("mouseover", function(d) {
var g = d3.select(this); // The node
var info = g.append('text')
.classed('info', true)
.attr('x', 20)
.attr('y', 10)
.text(function(d) { return d.name_ar + " " + d.sid });
})
.on("mouseout", function() {
// Remove the info text on mouse out.
d3.select(this).select('text.info').remove()
});
;
//rectagular nodes
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_ar; })
.style("fill-opacity", 1);
// Transition nodes to their new position.
//vertical
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.
//vertical
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("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("d", function(d) {
var o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
});
// Transition links to their new position.
link.transition()
.duration(duration)
.attr("d", diagonal);
// Transition exiting nodes to the parent's new position.
link.exit().transition()
.duration(duration)
.attr("d", function(d) {
var o = {x: source.x, y: source.y};
return diagonal({source: o, target: o});
})
.remove();
// Stash the old positions for transition.
nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});
}
// Toggle children on click.
function click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d);
}
</script>
<style>
.node {
cursor: pointer;
}
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 3px;
}
.node text {
font: 18px sans-serif;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 2px;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
PS: I changed to d.depth > 1 because it seems to me that you want to show 2 depths by default, not 3. If I'm wrong, just change that number accordingly.

Hierarchal Stacked Bar Chart

I've converted Mike Botock's Hierarchical Bar Chart to v4 and made some tweaks to fit my needs(vertical, tool-tip, widths of bars fit canvas, etc).
Now I'm trying to make this a stacked bar chart. In my JSON file I have two types of downtime Machine and Die. For the original chart I just add these up to get my overall but now i want to stack them and I'm unsure how to pull these out separately after doing a root.sum on the Hierarchy. This is my first chart so pardon some of the coding but feel free to correct me on anything. I also could clean some things up with if statements but I'm leaving everything separate as it is easier to troubleshoot. Any thoughts on how to make stacked hierarchical bar chart would be appreciated. Even if it means throwing away this code and starting over.
<body>
<script src="d3.min.js"></script>
<script>
//canvas variables
var margin = { top: 30, right: 120, bottom: 300, left: 120 },
width = 960 - margin.left - margin.right,
height = 800 - margin.top - margin.bottom;
// scale y on canvas from largest number to 0
var y = d3.scaleLinear().range([height, 0]);
var barWidth;
var barPadding = 5;
var oldBarWidth = width;
var depth = 0;
var color = d3.scaleOrdinal()
.range(["steelblue", "#ccc"]);
var duration = 750,
delay = 25;
//attach SVG to body with canvas variables declared above
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var divTooltip = d3.select("body").append("div").attr("class", "toolTip");
//attach a rectangle to the entire background for drilling
svg.append("rect")
.attr("class", "background")
.attr("width", width)
.attr("height", height)
.on("click", drillUp);
//append axis to the SVG
svg.append("g")
.attr("class", "yaxis");
svg.append("g")
.append("line")
.attr("transform", "translate(0," + height + ")")
.attr("x1", width)
.attr("stroke", "black")
.attr("shape-rendering", "crispEdges");
//import JSON file
d3.json("data/drilljson2.json", function (error, root) {
if (error) throw error;
//declare root of the JSON file
root = d3.hierarchy(root);
//add all children in hierarchy and get value for all parents
root.sum(function (d) { return (+d.DieDowntime + (+d.MachineDowntime)); });
//scale the 'Y' domain/axis from 0 to root value
y.domain([0, root.value]).nice();
//call the drill down function
drillDown(root, 0);
drillDown(root.children[3], 3);
});
function drillDown(d, i) {
if (!d.children) return;
// get the number of children to parent and calculate barWidth and keep track of depth of drill down.
numChildNodes = d.children.length;
barWidth = (width / numChildNodes) - barPadding;
depth += 1;
var end = duration + numChildNodes * delay;
// Mark any currently-displayed bars as exiting.
var exit = svg.selectAll(".enter")
.attr("class", "exit");
// Entering nodes immediately obscure the clicked-on bar, so hide it.
exit.selectAll("rect").filter(function (p) { return p === d; })
.style("fill-opacity", 0);
// Enter the new bars for the clicked-on data.
// Entering bars are immediately visible.
var enter = drillDownBars(d)
.attr("transform", stackDown(i))
.attr("width", oldBarWidth)
.style("opacity", 1);
// Update the y-scale domain.
y.domain([0, d3.max(d.children, function (d) { return d.value; })]).nice();
// Have the text fade-in, even though the bars are visible.
// Color the bars as parents; they will fade to children if appropriate.
enter.select("text").style("fill-opacity", 0);
enter.select("rect").style("fill", color(true));
// Update the y-axis.
svg.selectAll(".yaxis").transition()
.duration(duration)
.call(d3.axisLeft(y));
// Transition entering bars to their new position.
var enterTransition = enter.transition()
.duration(duration)
.delay(function (d, i) { return i * delay; })
.style("opacity", 1)
.attr("transform", function (d, i) { var transBar = (barWidth +barPadding) * i +barPadding; return "translate("+ transBar + ")"; });
// Transition entering text.
enterTransition.select("text")
.attr("transform", function (d) { return "translate("+(barWidth/2)+","+((height+5) + 10 * depth)+")rotate(90)" })
// working .attr("y", height + 15)
.style("fill-opacity", 1);
// Transition entering rects to the new y-scale.
enterTransition.select("rect")
.attr("y", function (d) { return y(d.value); })
.attr("height", function (d) { return height - y(d.value); })
.attr("width",barWidth)
.style("fill", function (d) { return color(!!d.children); });
// Transition exiting bars to fade out.
var exitTransition = exit.transition()
.duration(duration)
.style("opacity", 0)
.remove();
// Transition exiting bars to the new y-scale.
exitTransition.selectAll("rect")
.attr("y", function (d) { return y(d.value); })
.attr("height", function (d) { return height - y(d.value); });
// Rebind the current node to the background.
svg.select(".background")
.datum(d)
.transition()
.duration(end);
d.index = i;
oldBarWidth = barWidth;
}
function drillUp(d) {
if (!d.parent || this.__transition__) return;
numChildNodes = d.parent.children.length;
barWidth = (width / numChildNodes) - barPadding;
depth -= 1;
var end = duration + d.children.length * delay;
// Mark any currently-displayed bars as exiting.
var exit = svg.selectAll(".enter")
.attr("class", "exit");
// Enter the new bars for the clicked-on data's parent.
var enter = drillUpBars(d.parent)
.attr("transform", function (d, i) {
transBarWidth = (barWidth + barPadding) * i + barPadding;
return "translate(" + transBarWidth + "," + 0 + ")";
})
.style("opacity", 0);
// Color the bars as appropriate.
// Exiting nodes will obscure the parent bar, so hide it.
enter.select("rect")
.style("fill", function (d) { return color(!!d.children); })
.filter(function (p) { return p === d; })
.style("fill-opacity", 0);
// Update the y-scale domain.
y.domain([0, d3.max(d.parent.children, function (d) { return d.value; })]).nice();
// Update the y-axis.
svg.selectAll(".yaxis").transition()
.duration(duration)
.call(d3.axisLeft(y));
// Transition entering bars to fade in over the full duration.
var enterTransition = enter.transition()
.duration(end)
.style("opacity", 1);
// Transition entering rects to the new y-scale.
// When the entering parent rect is done, make it visible!
enterTransition.select("rect")
.attr("y", function (d) { return y(d.value); })
.attr("height", function (d) { return height - y(d.value); })
.on("end", function (p) { if (p === d) d3.select(this).style("fill-opacity", null); });
// Transition entering text.
enterTransition.select("text")
.attr("transform", function (d) { return "translate("+(barWidth/2)+","+((height+5) + 10 * depth)+")rotate(90)" })
.style("fill-opacity", 1);
// Transition exiting bars to the parent's position.
var exitTransition = exit.selectAll("g").transition()
.duration(duration)
.delay(function (d, i) { return i * delay; })
.attr("transform", stackUp(d.index));
// Transition exiting text to fade out.
exitTransition.select("text")
.style("fill-opacity", 0);
// Transition exiting rects to the new scale and fade to parent color.
exitTransition.select("rect")
.attr("y", function (d) { return y(d.value); })
.attr("height", function (d) { return height - y(d.value); })
.attr("width", barWidth)
.style("fill", color(true));
// Remove exiting nodes when the last child has finished transitioning.
exit.transition()
.duration(end)
.remove();
// Rebind the current parent to the background.
svg.select(".background")
.datum(d.parent)
.transition()
.duration(end);
oldBarWidth = barWidth;
}
// Creates a set of bars for the given data node, at the specified index.
function drillUpBars(d) {
var bar = svg.insert("g")
.attr("class", "enter")
.selectAll("g")
.data(d.children)
.enter().append("g")
.style("cursor", function (d) { return !d.children ? null : "pointer"; })
.on("click", drillDown);
bar.append("text")
.attr("dx", ".35em")
.attr("text-anchor", "middle")
.attr("transform", function (d) { return "translate(" + barWidth / 2 + "," + (height + 15) + ") rotate(90)" })
.text(function (d) { return d.data.name; });
bar.append("rect")
.attr("y", function (d) { return y(d.value); } )
.attr("height", function (d) { return height - y(d.value); })
.attr("width", barWidth)
.attr("stroke-width", 1)
.attr("stroke", "white");
return bar;
}
function drillDownBars(d) {
var bar = svg.insert("g")
.attr("class", "enter")
.selectAll("g")
.data(d.children)
.enter().append("g")
.style("cursor", function (d) { return !d.children ? null : "pointer"; })
.on("click", drillDown)
.on("mouseover", mouseover)
.on("mousemove", function (d) {
divTooltip
.text(d.data.name +" " + d.value)
.style("left", (d3.event.pageX - 34) + "px")
.style("top", (d3.event.pageY - 30) + "px");
});
bar.append("text")
.attr("dx", ".35em")
.attr("text-anchor", "middle")
.attr("transform", function (d) { return "translate(" + barWidth / 2 + "," + (height + 15 - y(d.value)) + ") rotate(90)" })
.text(function (d) { return d.data.name; });
bar.append("rect")
.attr("height", function (d) { return height - y(d.value); })
.attr("width", oldBarWidth)
.attr("stroke-width", 1)
.attr("stroke", "white");
return bar;
}
//Creates a stack of bars
function stackDown(i) {
var x0 = (oldBarWidth + barPadding) * i + barPadding;
var y0 = height;
return function (d) {
y0 -= height - y(d.value);
var ty = "translate(" + x0 + "," + y0 + ")";
return ty;
};
}
//
function stackUp(i) {
var x0 = barWidth * i + (barPadding * (i + 1));
var y0 = 0;
return function (d) {
var ty = "translate(" + x0 + "," + y0 + ")";
y0 -= height - y(d.value);
return ty;
};
}
function mouseover() {
divTooltip.style("display", "inline");
}
</script>
Here is a piece of the JSON file which could also use a little cleaning but minor details for now.
{
"name" : "Down Time",
"children" : [{
"name" : "2013",
"children" : [{
"name" : "May 2013",
"children" : [{
"name" : "21 May 2013",
"children" : [{
"name" : "110",
"children" : [{
"MachineDowntime" : ".00000000000000000000",
"DieDowntime" : ".50000000000000000000"
}
]
}, {
"name" : "115",
"children" : [{
"MachineDowntime" : "5.23333333333333333300",
"DieDowntime" : ".00000000000000000000"
}
]
}
]
}, {
"name" : "22 May 2013",
"children" : [{
"name" : "115",
"children" : [{
"MachineDowntime" : "2.96666666666666666730",
"DieDowntime" : ".00000000000000000000"
}
]
}, {
"name" : "110",
"children" : [{
"MachineDowntime" : ".00000000000000000000",
"DieDowntime" : "10.36666666666666667000"

How to mix zoom and drag functions in a graph?

Having an atlas force graph with setup as follow, I would like to zoom in and out on mouse wheel events from anywhere in the drawing area but nodes (circles) in order to allow dragging individual nodes.
var svg = graph.append("svg")
.attr("width", width)
.attr("height", height)
.attr("pointer-events", "all")
.call(d3.behavior.zoom().on("zoom", redraw))
.append('g');
var link = svg.selectAll(".link")
.data(links)
.enter().append("line")
.attr("class", "link")
var node = svg.selectAll(".node")
.data(nodes)
.enter().append("svg:g")
.attr("class", "node")
.on("dblclick", dblclick)
.call(force.drag);
node.append("circle")
.attr("class", "circle");
function redraw() {
svg.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")");
}
force.on("tick", function() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
});
The issue I have with this code is that clicking on a node and dragging it drags the whole graph, whereas when removing the call(... redraw) part it would let me drag individual nodes.
Is there a way to mix both behaviors and either prevent zooming when pointer is inside a node, or have node event prevalent on global (svg) events?
<!DOCTYPE html>
<html>
<head>
<title>Fidlde</title>
<script type="text/javascript" src="d3-master/d3.v3.min.js"></script>
<style>
.circle {
fill: #F5F5F5;
stroke: #999999;
stroke-width: 3;
}
.node text {
pointer-events: none;
font: 10px sans-serif;
}
.link {
stroke: #999999;
stroke-opacity: .6;
stroke-width: 3;
}
</style>
</head>
<body>
<div id="graph">Hello!</div>
<script>
// graph size
var width = 400;
var height = 400;
var nodes = [{name: 'A'}, {name: 'B'}, {name: 'C'}, {name: 'D'}];
var edges = [{source: 'A', target: 'B'}, {source: 'B', target: 'C'}, {source: 'C', target: 'A'}, {source: 'C', target: 'D'}];
var nodeMap = {};
nodes.forEach(function(x) { nodeMap[x.name] = x; });
var links = edges.map(function(x) {
return { source: nodeMap[x.source], target: nodeMap[x.target], value: 1 };
});
var graph = d3.select("#graph");
var svg = graph.append("svg")
.attr("width", width)
.attr("height", height)
.attr("pointer-events", "all")
.call(d3.behavior.zoom().on("zoom", redraw))
.append('g');
var force = d3.layout.force()
.gravity(.25)
.distance(140)
.charge(-3500)
.size([width, height]);
/* Issue was here, the following code addresses it.
Thanks to Lars and Cool Blue - see comments
var drag = force.drag()
.on("dragstart", dragstart);
*/
var stdDragStart = force.drag().on("dragstart.force");
force.drag()
.on("dragstart", function(d){
//prevent dragging on the nodes from dragging the canvas
d3.event.sourceEvent.stopPropagation();
stdDragStart.call(this, d);
});
force
.nodes(nodes)
.links(links)
.friction(0.8)
.start();
var link = svg.selectAll(".link")
.data(links)
.enter().append("line")
.attr("class", "link");
var node = svg.selectAll(".node")
.data(nodes)
.enter().append("svg:g")
.attr("class", "node")
.on("dblclick", dblclick)
.call(force.drag);
node.append("circle")
.attr("class", "circle")
.attr("r", 10);
node.append("text")
.attr("dx", -4)
.attr("dy", ".35em")
.text(function(d) { return d.name; });
force.on("tick", function() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
});
// redraw after zooming
function redraw() {
svg.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")");
}
function dblclick(d) {
d3.select(this).classed("fixed", d.fixed = false);
}
function dragstart(d) {
d3.select(this).classed("fixed", d.fixed = true);
}
</script>
</body>
</html>
In oder to address the remaining dragging node issue, I made the following changes in the code:
node.enter()
.append("svg:g")
.attr("pointer-events", "all")
.attr("id", function(d) { return '_'+d.name })
.attr("class", "node")
.on("click", nodeClick)
.on("dblclick", nodeDoubleClick)
.on("mouseover", nodeMouseOver)
.on("mouseout", nodeMouseOut)
.call(force.drag);
function nodeClick(d) {
// fix the current node to its position
d.fixed = true;
}
function nodeDoubleClick(d) {
// release the current node
d.fixed = false;
}
function nodeMouseOver(d) {
// move the current node to front - some nodes are overlapping each others
var sel = d3.select(this);
sel.moveToFront();
// stop the whole graph
force.stop();
}
function nodeMouseOut(d) {
// resume node motion
force.start();
}
I also removed the following dragstart function which remained from previous code and was probably called while zooming.
/* function dragstart(d) {
d3.select(this).classed("fixed", d.fixed = true);
}
*/
Everything is now properly working. Thank you all for your contributions.
try this snippet of code :) also works
var width=600;
var height=600;
var nodes=[{
"name":"n1"
},{
"name":"n2"
},{
"name":"n3"
},{
"name":"n4"
},{
"name":"n5"
}];
var links=[{"source":0,"target":1},
{"source":0,"target":2},
{"source":0,"target":3},
{"source":1,"target":4},
{"source":2,"target":4},
{"source":3,"target":2}];
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.attr("transform","translate(200,200)");
svg.append("rect")
.attr("width",width)
.attr("height",height)
.attr("fill","none")
.attr("pointer-events","all")
.call(d3.behavior.zoom().on("zoom", redraw));;
var force=d3.layout.force().charge(-400).linkDistance(200);
force.nodes(nodes).links(links).start();
var link = svg.selectAll(".link")
.data(links)
.enter().append("line")
.attr("class", "link")
var node = svg.selectAll("circle")
.data(nodes)
.enter()
.append("circle")
.attr("class","circle")
.call(force.drag);
function redraw() {
svg.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")");
}
force.on("tick", function() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
});

Resources