My understanding of d3 is currently rather limited and I am currently fiddling with a dendrogram example of D3.js. It can be found on several places:
on this interactive version for example.
When I implement it, all goes fine until you try to update a property like the circle diameter of the nodes. If I do (using an interactive framework like AngularJS which watches the parameter change): the nodes change in size. So no problem yet. However if I then click one of the nodes, the size is reset to the initialization size instead of the new one.
when a node gets clicked it follow the click function:
var nodeEnter = node.enter().append("g")
.attr("class", "dendrogramnode2")
.on("click", click);
The click function calls an update function.
function click(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d);
}
Which then updates the dendrogram and opens or closes the necessary nodes.
function update(source) {
// Compute the new tree layout.
var nodes = tree.nodes(root),
links = tree.links(nodes);
// Normalize for fixed-depth.
nodes.forEach(function(d) { d.y = d.depth * 80; });
// 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 "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; })
.on("click", click);
nodeEnter.append("circle")
.attr("r", 1e-6)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
nodeEnter.append("text")
.attr("x", 10)
.attr("dy", ".35em")
.attr("text-anchor", "start")
//.attr("transform", function(d) { return d.x < 180 ? "translate(0)" : "rotate(180)translate(-" + (d.name.length * 8.5) + ")"; })
.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 "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; })
nodeUpdate.select("circle")
.attr("r", 4.5)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
nodeUpdate.select("text")
.style("fill-opacity", 1)
.attr("transform", function(d) { return d.x < 180 ? "translate(0)" : "rotate(180)translate(-" + (d.name.length + 50) + ")"; });
// TODO: appropriate transform
var nodeExit = node.exit().transition()
.duration(duration)
//.attr("transform", function(d) { return "diagonal(" + 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;
});
}
This update function is thus called:
at initialization --> no problem (example: circle r = 5)
when a parameter get updated --> no problem, the parameter updates. (example: circle r = 10)
when you click a node --> problematic--> graph takes initial parameters.(example: circle r = 5)
All of this probably has a lot to do with scoping and how javascript handles databinding but I don't know how to do this properly. I either need to be able to access the new properties instead of the old ones.
Is there a way to either
adapt the code so the new parameter is taken instead of the old ones?
bind the parameters to the svg group as an object (probably not as efficient? ) so I
can manually reach for it from whatever scope using the d3 selectors?
I have set a property to the DOM element for those attributes which don't differ per datum.
function dograph(p){
//paramater object is passed and it's name is "p"
d3.select(elementid).selectAll("svg")[0][0]["p"] = p
//at some point update function gets called as part of an event and p is no longer available.
//someSvgElement
.on("mouseover"){update())}
function update(source) {
var p = d3.select(elementid).selectAll("svg")[0][0]["p"];
//stuff happens
}
}
might not be the perfect solution but it works for me.
Related
I am working on a project which needs a label for each of the levels of the collapsible tree in D3.js(https://bl.ocks.org/mbostock/4339083). I am facing tough time in adding the same. The label I require is added in the attached screenshot. The label should populate for each level as soon as click on each level and disappear as it the tree rolls back. Could anyone help me out with this.
Modify the update method to track the levels from the node items. Maintain a unique sorted hash of all the depth values from the node items used to plot the chart. Once you have the sorted depthHash array, plot the text on the top of your chart. Below is a fiddle i have modified for your reference.
http://jsfiddle.net/deepakpster/vomxqxov/3/
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]; });
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 + ")");
flare = "http://rawgit.com/mbostock/1093025/raw/a05a94858375bd0ae023f6950a2b13fac5127637/flare.json"
d3.json(flare, function(error, flare) {
root = flare;
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);
});
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; });
// Showing the labels for the level of depths.
// Using underscore.js to do the pluck, uniq.
var depthHash = _.uniq(_.pluck(nodes, "depth")).sort();
svg.selectAll("g.levels-svg").remove();
var levelSVG = svg.append("g").attr("class", "levels-svg");
var levels = levelSVG.selectAll("g.level");
levels.data(depthHash)
.enter().append("g")
.attr("class", "level")
.attr("transform", function(d) { return "translate(" + d*180 + "," + 10 + ")"; })
.append("text")
.text(function(d){
return "level-" + d;
});
// 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"; });
*/
var ww = 30, hh = 20
nodeEnter.append("rect")
.attr("height", 1e-6)
.attr("width", 1e-6)
.attr("x", -ww/2)
.attr("y", -hh/2)
.attr("rx", 3)
.attr("ry", 3)
.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("rect")
.attr("width", ww)
.attr("height", hh)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
nodeUpdate.select("circle")
.attr("r", 4.5)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
nodeUpdate.select("text")
.attr("dx", -10)
.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);
}
I am using d3.tree to create my tree hierarchy, I am relatively new to this lib, so I need a little help.
var treeData = {{ data | safe }};
// Set the dimensions and margins of the diagram
var margin = {top: 30, right: 90, bottom: 30, left: 150},
width = $('#tree-container').width(),
height = $('#tree-container').height();
// 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-container").append("svg")
.attr("width", width)
.attr("height", height)
.call(d3.zoom().on("zoom", function () {
svg.attr("transform", d3.event.transform)
}))
.append("g")
.attr("width", width)
.attr("height", height)
.attr("id", "place")
.attr("transform", "translate("
+ (width/2) + "," + margin.top + ")");
var i = 0,
duration = 750,
root;
// declares a tree layout and assigns the size
var treemap = d3.tree()
.nodeSize([70, 10]);
// Assigns parent, children, height, depth
root = d3.hierarchy(treeData, function(d) { return d.children; });
root.x0 = 0;
root.y0 = width / 2;
// 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
}
}
var nodes;
function update(source) {
// Assigns the x and y position for the nodes
var treeData = treemap(root);
// Compute the new tree layout.
nodes = treeData.descendants();
links = treeData.descendants().slice(1);
// Normalize for fixed-depth.
nodes.forEach(function(d){ //HERE
d.y = d.depth * 120;
});
// ****************** 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.x0 + "," + source.y0 + ")";
});
// Add Circle for the nodes
nodeEnter.append('circle')
.attr('class', 'node')
.attr('id', function(d) { return "circle-"+d.data.name; })
.attr('r', 1e-6)
.style("fill", function(d) {
return d._children ? "lightsteelblue" : "#fff";// make text color appear read or as data.color
}).on('click', click);
// Add labels for the nodes
nodeEnter.append('text')
.attr("dy", "0.45em")
.attr("y", function(d) {
return d.children || d._children ? -13 : 13;
})
.attr("text-anchor", function(d) {
return d.children || d._children ? "end" : "start";
})
.attr("cursor", "pointer")
.text(function(d) { return d.data.name; })
.on("click", textClick);
// 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 ? d.data.ncolor : "#fff"; }) // change color of inner circle
.style("stroke", function (d) { return d.data.ncolor; }) // changing color of outere circle
.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")
.style("stroke", function (d) { return d.data.color; }) // Place where color of previous link changes
.attr('d', function(d){
var o = {x: source.x0, y: source.y0};
return diagonal(o, o)
});
// UPDATE
var linkUpdate = linkEnter.merge(link);
// Transition back to the parent element position
linkUpdate.transition()
.duration(duration)
.attr('d', function(d){ return diagonal(d, d.parent) });
// Remove any exiting links
var linkExit = link.exit().transition()
.duration(duration)
.attr('d', function(d) {
var o = {x: source.x, y: source.y};
return diagonal(o, o)
})
.remove();
// Store the old positions for transition.
nodes.forEach(function(d){
d.x0 = d.x;
d.y0 = d.y;
});
// Creates a curved (diagonal) path from parent to the child nodes
function diagonal(s, d) {
path = "M" + s.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(d) {
conosle.log();
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d);
}
It actually works, but what I am looking for is the way to have everything inside my viewing window. Like if someone click on node it expands and if children nodes overflow(go out of the window), I need to zoom out, so they will be visible. Hope there is d3 jedi-master to answer me :)))
This is very hard to answer without seeing your actual data or a running version of your code, but here is a suggestion. When you do this:
var treemap = d3.tree()
.nodeSize([70, 10]);
You're setting the size of each node, but not the whole layout. Also, according to the API,
When a node size is specified, the root node is always positioned at ⟨0, 0⟩.
Here is an example: I just forked Bostock's tree example, setting the nodeSize, you can see that the nodes are going outside the SVG: http://blockbuilder.org/anonymous/7a84944610c7e6b3b9ebf063977955c9
So, a possible solution is using size instead of nodeSize:
var treemap = d3.tree()
.nodeSize([width, height]);
Here is the original tree example using size, for comparison: http://blockbuilder.org/mbostock/4339083
I'm trying to create a tree using D3 and am having trouble changing the text of my nodes after changing dataset. My code for updating/creating the tree is pasted below:
function update(source) {
var duration = d3.event && d3.event.altKey ? 5000 : 500;
// Compute the new tree layout.
var nodes = tree.nodes(root).reverse();
// Normalize for fixed-depth.
nodes.forEach(function(d) { d.y = d.depth * 60; });
// Update the nodes…
var node = vis.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("svg:g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
.on("click", function(d) { toggle(d); update(d); });
nodeEnter.append("svg:circle")
.attr("r", 1e-6)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
nodeEnter.append("svg: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) { console.log(d.name); 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", function(d) {return d.size;} )//14.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 = vis.selectAll("path.link")
.data(tree.links(nodes), function(d) { return d.target.id; });
// Enter any new links at the parent's previous position.
link.enter().insert("svg:path", "g")
.attr("class", "link")
.attr("d", function(d) {
var o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
})
.transition()
.duration(duration)
.attr("d", diagonal);
// 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;
});
}
On tree one you can see the first tree with each node having a text.
On tree two you can see how of the same text names, where as tree two has completely different node texts than the first first. It creates a mix of node texts from tree one and tree two.
My new data HAS all the new texts I want to use, but when I use console.log() to print them out it only prints out the few that it actually uses on tree two.
How do I make it update the text on all nodes?
You are not updating the text in the update selection. To do that, use something like the following code:
nodeUpdate.select("text")
.text(function(d) { console.log(d.name); return d.name; })
.style("fill-opacity", 1);
Please see http://bl.ocks.org/mbostock/4339083
It loads data from flare.json and displays the nodes in a tree layout. I want to do the following:
1. Write a function to display only some of the nodes based on some conditions and reload the tree.
2. Write a function to add some nodes and reload the tree.
3. Write a function to remove some nodes and reload the tree.
I need to call these functions from outside
d3.json("/d/4063550/flare.json", function(error, flare)
in that sample.
Please let me know how to do it. I tried .children.splice method and again called upload(root). But it did not work.
Here is the relevant part of the code:
d3.json("/d/4063550/flare.json", function(error, flare) {
root = flare;
root.x0 = height / 2;
root.y0 = 0;
function collapse(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}
root.children.forEach(collapse);
update(root);
});
function update(source) {
// Compute the new tree layout.
var nodes = tree.nodes(root).reverse(),
links = tree.links(nodes);
// 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 + ")"; })
nodeEnter.append("circle")
.attr("r", 1e-6)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#fff"; });
// 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"; });
// 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);
// 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;
});
}
I changed your code a little bit and it works for me:
d3.json("flare.json", function(json) {
root = json;
root.fixed = true;
root.x = w / 2;
root.y = h / 2 - 80;
console.log("haha");
firstTimeRun();
update();
});
function firstTimeRun(){
flatten(root).forEach(collapse);
}
function collapse(d) {
if (d.children) {
d._children = d.children;
d.children = null;
}
}
I'm using D3.js to plot a collapsible tree diagram like in the example. It's working mostly well, but the diagram might change dramatically in size when it enters its normal function (ie instead of the few nodes I have now, I'll have a lot more).
I wanted to make the SVG area scroll, I've tried everything I found online to make it work, but with no success. The best I got working was using the d3.behaviour.drag, in which I drag the whole diagram around. It is far from optimal and glitches a lot, but it is kinda usable.
Even so, I'm trying to clean it up a little bit and I realised the d3.behaviour.zoom can also be used to pan the SVG area, according to the API docs.
Question: Can anyone explain how to adapt it to my code?
I would like to be able to pan the SVG area with the diagram, if possible making it react to some misuses, namely, trying to pan the diagram out of the viewport, and enabling to zoom to the maximum viewport's dimensions...
This is my code so far:
var realWidth = window.innerWidth;
var realHeight = window.innerHeight;
function load(){
callD3();
}
var m = [40, 240, 40, 240],
w = realWidth -m[0] -m[0],
h = realHeight -m[0] -m[2],
i = 0,
root;
var tree = d3.layout.tree()
.size([h, w]);
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.y, d.x]; });
var vis = d3.select("#box").append("svg:svg")
.attr("class","svg_container")
.attr("width", w)
.attr("height", h)
.style("overflow", "scroll")
.style("background-color","#EEEEEE")
.append("svg:g")
.attr("class","drawarea")
.attr("transform", "translate(" + m[3] + "," + m[0] + ")")
;
var botao = d3.select("#form #button");
function callD3() {
//d3.json(filename, function(json) {
d3.json("D3_NEWCO_tree.json", function(json) {
root = json;
d3.select("#processName").html(root.text);
root.x0 = h / 2;
root.y0 = 0;
botao.on("click", function(){toggle(root); update(root);});
update(root);
});
function update(source) {
var duration = d3.event && d3.event.altKey ? 5000 : 500;
// Compute the new tree layout.
var nodes = tree.nodes(root).reverse();
// Normalize for fixed-depth.
nodes.forEach(function(d) { d.y = d.depth * 50; });
// Update the nodes…
var node = vis.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("svg:g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + source.y0 + "," + source.x0 + ")"; })
.on("click", function(d) { toggle(d); update(d); });
nodeEnter.append("svg:circle")
.attr("r", function(d){
return Math.sqrt((d.part_cc_p*1))+4;
})
.attr("class", function(d) { return "level"+d.part_level; })
.style("stroke", function(d){
if(d._children){return "blue";}
})
;
nodeEnter.append("svg:text")
.attr("x", function(d) { return d.children || d._children ? -((Math.sqrt((d.part_cc_p*1))+6)+this.getComputedTextLength() ) : Math.sqrt((d.part_cc_p*1))+6; })
.attr("y", function(d) { return d.children || d._children ? -7 : 0; })
.attr("dy", ".35em")
.attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
.text(function(d) {
if(d.part_level>0){return d.name;}
else
if(d.part_multi>1){return "Part " + d.name+ " ["+d.part_multi+"]";}
else{return "Part " + d.name;}
})
.attr("title",
function(d){
var node_type_desc;
if(d.part_level!=0){node_type_desc = "Labour";}else{node_type_desc = "Component";}
return ("Part Name: "+d.text+"<br/>Part type: "+d.part_type+"<br/>Cost so far: "+d3.round(d.part_cc, 2)+"€<br/>"+"<br/>"+node_type_desc+" cost at this node: "+d3.round(d.part_cost, 2)+"€<br/>"+"Total cost added by this node: "+d3.round(d.part_cost*d.part_multi, 2)+"€<br/>"+"Node multiplicity: "+d.part_multi);
})
.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", function(d){
return Math.sqrt((d.part_cc_p*1))+4;
})
.attr("class", function(d) { return "level"+d.part_level; })
.style("stroke", function(d){
if(d._children){return "blue";}else{return null;}
})
;
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", function(d){
return Math.sqrt((d.part_cc_p*1))+4;
});
nodeExit.select("text")
.style("fill-opacity", 1e-6);
// Update the links…
var link = vis.selectAll("path.link")
.data(tree.links(nodes), function(d) { return d.target.id; });
// Enter any new links at the parent's previous position.
link.enter().insert("svg:path", "g")
.attr("class", "link")
.attr("d", function(d) {
var o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
})
.transition()
.duration(duration)
.attr("d", diagonal);
// 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();
$('svg text').tipsy({
fade:true,
gravity: 'nw',
html:true
});
// Stash the old positions for transition.
nodes.forEach(function(d) {
d.x0 = d.x;
d.y0 = d.y;
});
var drag = d3.behavior.drag()
.origin(function() {
var t = d3.select(this);
return {x: t.attr("x"), y: t.attr("y")};
})
.on("drag", dragmove);
d3.select(".drawarea").call(drag);
}
// Toggle children.
function toggle(d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
}
function dragmove(){
d3.transition(d3.select(".drawarea"))
.attr("transform", "translate(" + d3.event.x +"," + d3.event.y + ")");
}
}
You can see (most of) a working implementation here: http://jsfiddle.net/nrabinowitz/fF4L4/2/
The key pieces here:
Call d3.behavior.zoom() on the svg element. This requires the svg element to have pointer-events: all set. You can also call this on a subelement, but I don't see a reason if you want the whole thing to pan and zoom, since you basically want the whole SVG area to respond to pan/zoom events.
d3.select("svg")
.call(d3.behavior.zoom()
.scaleExtent([0.5, 5])
.on("zoom", zoom));
Setting scaleExtent here gives you the ability to limit the zoom scale. You can set it to [1, 1] to disable zooming entirely, or set it programmatically to the max size of your content, if that's what you want (I wasn't sure exactly what was desired here).
The zoom function is similar to your dragmove function, but includes the scale factor and sets limits on the pan offset (as far as I can tell, d3 doesn't have any built-in panExtent support):
function zoom() {
var scale = d3.event.scale,
translation = d3.event.translate,
tbound = -h * scale,
bbound = h * scale,
lbound = (-w + m[1]) * scale,
rbound = (w - m[3]) * 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 + ")");
}
(To be honest, I don't think I have the logic quite right here for the correct left and right thresholds - this doesn't seem to limit dragging properly when zoomed in. Left as an exercise for the reader :).)
To make things simpler here, it helps to have the g.drawarea element not have an initial transform - so I added another g element to the outer wrappers to set the margin offset:
vis // snip
.append("svg:g")
.attr("class","drawarea")
.append("svg:g")
.attr("transform", "translate(" + m[3] + "," + m[0] + ")");
The rest of the changes here are just to make your code work better in JSFiddle. There are a few missing details here, but hopefully this is enough to get you started.