Right now I am trying to separate my rectangle nodes because they overlap as shown in the picture below:
I took a look and found out that D3 offers a nodeSize and separation method but for some reason it did not work.
I found this blog post talking about the issue but he says
The size property doesn’t exist in nodes, so it will be whatever property you want to control the size of them.
but clearly there is a nodeSize method so I feel like I am simply using the method incorrectly and/or the blog post is out-of-date. I want to shape my nodes to be the size of the rectangle and space them out evenly so they do not overlap each other. Does anyone know how to use the methods properly? The documentation about these methods isn't explained very well and it isn't yielding any difference. I also couldn't find many examples where people changed the nodeSize of trees or needed separation for rectangular objects (there were some examples regarding circular ones but I feel that's too different...)
Here is the relevant code. I will try to prepare a JSFiddle.
var margin = {top: 20, right: 120, bottom: 20, left: 120},
height = 960 - margin.right - margin.left,
width = 800 - margin.top - margin.bottom,
rectW = 70;
rectH = 30;
//bbox = NaN,
maxTextLength = 0;
var i = 0,
duration = 750,
root;
//paths from each node drawn initially here
//changed to d.x, d.y
var diagonal = d3.svg.diagonal()
.projection(function(d) { return [d.x+rectW/2, d.y+rectH/2];
//.projection(function(d) { return [d.x+bbox.getBBox().width/2, d.y+bbox.getBBox().height/2];
});
var tree = d3.layout.tree()
.nodeSize([30,70])
.separation(function(a, b) { return (a.parent == b.parent ? 1 : 2); })
.size([width, height]);
var svg = d3.select("body")
.append("svg")
.attr("height","100%").attr("width","100%")
.call(d3.behavior.zoom().on("zoom", redraw))
.append("g")
.attr("transform", "translate(" + margin.top + "," + margin.left + ")");
UPDATE 05/04/2018: It is my understanding d3 has changed a lot (for the better) to be a lot more modular. For those who are looking towards this answer, this was using a much older version of d3 (specifically v3).
A lot of the findings are still relevant for the d3-hierarchy package under cluster.size() and cluster.nodeSize() and I am planning to potentially update my example to use that. For historical reference though, I'm leaving the bottom untouched.
Here is a jsFiddle: http://jsfiddle.net/augburto/YMa2y/
EDIT: Updated and move the example to Codepen. The example still exists on jsFiddle but Codepen seems to have a nicer editor and allows you to easily fork. I'll also try to add the example directly to this answer once I've reduced the amount of content in it.
http://codepen.io/augbog/pen/LEXZKK
Updating this answer. I talked with my friend and we looked at the source for size and nodeSize
tree.size = function(x) {
if (!arguments.length) return nodeSize ? null : size;
nodeSize = (size = x) == null;
return tree;
};
tree.nodeSize = function(x) {
if (!arguments.length) return nodeSize ? size : null;
nodeSize = (size = x) != null;
return tree;
};
When you set a size for the tree, you are setting a fixed size so that the tree has to conform to that width and height. When you set a nodeSize, the tree has to be dynamic so it resets the size of the tree.
When I specified size after nodeSize, I was pretty much overriding what I wanted haha...
Bottom line: If you want nodeSize to work, you can't have a fixed tree size. It will set the size to null. Do not declare a size if you are declaring a nodeSize.
EDIT: D3.js actually updated the documentation. Thanks to whoever did that because it is way clearer now!
The nodeSize property is exclusive with tree.size; setting
tree.nodeSize sets tree.size to null.
This is what my tree looks like now. I have also added zoom functionality as well as how to center text within the rectangle.
I didn't quite understand the accepted answer until I did some digging of my own, so I thought I'd share what I found as well...
If you are using .size() and your nodes are overlapping, use .nodeSize() instead
As explained in the accepted answer, .size() sets the tree's available size, and so depending on the spacing between cousin nodes, second cousins, etc. they may get squished together and overlap. Using .nodeSize() simply says each node should get this much space, so they will never overlap!
The code that ended up working for me was
var nodeWidth = 300;
var nodeHeight = 75;
var horizontalSeparationBetweenNodes = 16;
var verticalSeparationBetweenNodes = 128;
var tree = d3.layout.tree()
.nodeSize([nodeWidth + horizontalSeparationBetweenNodes, nodeHeight + verticalSeparationBetweenNodes])
.separation(function(a, b) {
return a.parent == b.parent ? 1 : 1.25;
});
Without horizontalSeparationBetweenNodes and verticalSeparationBetweenNodes the nodes edges were touching each other. I also added this .separation() to decrease the amount of space between cousin nodes, as my nodes are pretty wide and lots of space was getting wasted.
Note: This is for d3 v3, not v4
First, thanks to all those who posted before, pure gold.
I wanted to add to this post for those that might be struggling with the offset problem associated with a horizontally drawn tree.
The key is, if you switch from .size() to .nodeSize() on a horizontal tree, you'll notice your root node seems to jump/reorient to be located at (0,0).
And per the d3.js documentation this is actually the case (see https://github.com/d3/d3-hierarchy/blob/master/README.md#tree_nodeSize )
However, to adjust you just need to make sure to reorient your viewBox.
That is to say, when you .append your svg you need to explicitly set your viewBox. Here's my hacky little line where it worked for me...
svg = d3.select("#tree").append("svg")
.attr("width", width + margin.right + margin.left)
.attr("height", height + 0 + 0)
.attr("viewBox", "0 "+(-1*(height-margin.top-margin.bottom)/2)+" "+width+" "+height)
.append("g")
.attr("transform", "translate("
+ margin.left + "," + 0 + ")");
D3 now does things through Observable.
To set the nodeSize look for the line:
main.variable(observer("tree")).define("tree", ["d3","dx","dy"],
function(d3,dx,dy){return(
d3.tree()
And set nodeSize with added constants:
main.variable(observer("tree")).define("tree", ["d3","dx","dy"],
function(d3,dx,dy){return(
d3.tree().nodeSize([dx + 10, dy + 10])
Or use a function to set values wrt chart size as discussed in other answer using the older D3 approach.
Related
I created this fiddle for a simple tree visualisation with d3js. It works fine. However, when the tree gets really big I have the problem than texts next to the nodes tend to overlap. So I need to somehow set a vertical distance. How can I achieve this? The following image shows what I mean:
I tried to add it with the separation function, but this is I guess only changes it horizontally.
var tree = d3.layout.tree().nodeSize([1, nodeHeight])
.separation(function(a, b) {
var height = a.height + b.width,
distance = height / 2 + 50;
return distance;
}),
nodes = tree.nodes(data),
links = tree.links(nodes);
I think the sibling nodes are not overlapping but the cousins. To handle your problem, you need to see how tree.separation() works.
In one of my projects. I did this.
var tree = d3.layout.tree();
tree.nodeSize(/*some stuff here*/)
.separation(function(a, b) {
return (a.parent == b.parent ? 1 : 1.5);
});
return (a.parent == b.parent ? 1 : 1.5) basically is saying that if
nodes have same parent or are siblings, then separation between them is none and if they don't have the same parents, they are considered cousins, and therefore computed distance between them is 50% the height of your node(which you defined in nodeSize).
I'm not good at explaining stuff like professionals do but definitely check out separation method and keep in mind it handles distance between cousins nodes.
I had a similar issue, and none of the answers to related questions that suggested using nodeSize() or separation() appeared to change the layout much (or, in ways that I was expecting).
In the end, I made the following simple scaling change in the update() function, and it fixed the issues with vertically overlapping nodes. It's not terribly elegant, but has the virtue of being simple:
nodes.forEach((d) => {
// spread out the vertical axis (if this isn't here, lines tend to overlap on denser graphs)
d.x = d.x * 2;
});
I am working on this plnkr. I have three lines at angle 30, 45 and 60. I want to apply a brush on these lines so that when the chart is brushed the lines get redrawn at where it crossed the brushed rectangle with appropriate the values on the axis. Any help or hint to solve this problem is greatly appreciated.
EDIT: If you have different solutions to draw the rotated lines and brush on top of them it is welcomed too. Please help.
var ga = d3.select("svg")
.append("g")
.attr("class", "a axis")
.attr("transform", "translate(" + margin.left + "," + (height + margin.top) + ")")
.selectAll("g")
.data([30, 45, 60])
.enter()
.append("g")
.attr("class", "rotatedlines")
.attr("transform", function(d) { return "rotate(" + -d + ")"; })
.attr("stroke-width", 1)
.attr("stroke", "black")
.attr("stroke-dasharray", "5,5");
To explain my solution:
The fundamental steps to take are as follows:
update the domains of the x and y scales to the brush extent
redraw the axes
compute the scale factor and translation for the lines
scale and translate the line containers accordingly
reset the brush
Note that steps 3 and 4 are only necessary because you're not using the scales to draw everything -- a better approach would be to define two points for each line as the data that's bound to the elements and then use the scales to redraw. This would make the code simpler.
With your approach it's still possible though. In order to facilitate it, I've made a few modifications to your code -- in particular, I've cleaned up the various nested g elements with different translations and defined the lines through their x1, x2, y1, y2 attributes rather than through translation of the containers. Both of these changes make the functionality you want easier to implement as only a single transformation takes places that doesn't need to consider multiple other transformations. I've also nested the lines in multiple g elements so that they can be scaled and translated more easily.
The brush handler function now looks like this:
// update scales, redraw axes
var extent = brush.extent();
x.domain(brush.empty() ? x2.domain() : [ extent[0][0], extent[1][0] ]);
y.domain(brush.empty() ? y2.domain() : [ extent[0][1], extent[1][1] ]);
xAxisG.call(xAxis);
yAxisG.call(yAxis);
This code should be fairly self-explanatory -- the domains of the scales are updated according to the current extent of the brush and the axes are redrawn.
// compute and apply scaling and transformation of the g elements containing the lines
var sx = (x2.domain()[1] - x2.domain()[0])/(x.domain()[1] - x.domain()[0]),
sy = (y2.domain()[1] - y2.domain()[0])/(y.domain()[1] - y.domain()[0]),
dx = -x2(x.domain()[0]) - x2.range()[0],
dy = -y2(y.domain()[1]) - y2.range()[1];
d3.selectAll("g.container")
.attr("transform", "translate(" + [sx * dx, sy * dy] + ")scale(" + [sx, sy] + ")");
This is the tricky part -- based on the new domains of the scales, we need to compute the scale and translation for the lines. The scaling factors are simply the ratio of the old extent to the new extent (note that I have made copies of the scales that are not modified), i.e. a number greater than 1. The translation determines the shift of the (0,0) coordinate and is computed through the difference of the old (0,0) coordinate (I get this from the range of the original scales) and the position of the new domain origin according to the original scales.
When applying the translation and scale at the same time, we need to multiply the offsets with the scaling factors.
// reset brush
brush.clear();
d3.select(".brush").call(brush);
Finally, we clear the brush and reset it to get rid of the grey rectangle.
Complete demo here.
You can access the brush extent via d3.event.target.extent(). The flow for drawing the scale is this:
Set scale
Set axis
Draw axis
As soon as the brush is done, you have to modify the scale and then re-draw the axis according to the current x and y domain. Is that what you meant?
I cleaned up the code a bit and made a little demonstration: http://plnkr.co/edit/epKbXbcBR2MiwUOMlU5A?p=preview
I re-factored the d3.layout.pack graph example here into a reusable module. Now I want to update the graph when the data updates. But when I call the graph with the new data the new graph gets rendered on top of the old graph. You can find a demo of the issue here.
Basically, to simulate the data update I am calling a function with setinterval this way:
function test(){
d3.select('#vis')
.datum(data2)
.call(cluster);
}
setInterval(test, 1500);
you can find the data update section in the bottom of the file.
Could you please check what's wrong?
There are a few problems with your code. First, your check whether the SVG exists already doesn't work because of scoping issues. The better way to do it is to select the element you want and check whether your selection is empty.
var svg = d3.select("svg > g");
if(svg.empty()){
svg = d3.select(this).append("svg:svg").attr("width", width)
.attr("height", height)
.append("svg:g")
.attr("transform", "translate(" + (width - r) / 2 + "," + (height - r) / 2 + ")");
}
Note that I've merged the appending of the g element into this, as that is what you're operating on.
Second, you need to handle the update and exit selections in addition to the enter selection. I've added that to your jsfiddle here.
This is a continuation of my efforts to build a collapsible tree layout using d3.js.
Generate (multilevel) flare.json data format from flat json
The layout looks like: (http://bl.ocks.org/mbostock/raw/4339083/) with around 3k nodes and depth of some nodes around 25. The current size of the canvas I need to set is 8000px width and 8000px height in order that all nodes are visible which I know is not reasonable when the number of tree levels rendered is 2 or 3.
Furthermore, I intend to make this code reusable with other trees that maybe smaller/larger in size based on what data source(json file) is selected.
So I was wondering if it is possible to resize the canvas size relative to the positions of the nodes/ number of nodes shown on screen. This way, the code would be much more systematic and adaptable.
I saw this:
Dynamically resize the d3 tree layout based on number of childnodes
but this resizes the tree, which if you can imagine in a case of tree with around 3k nodes, makes it hard to read and comprehend.
I know this might not even be related to d3.js but I tagged it to explain my issue and bring in d3 experts too who might have faced a similar condition.
I am also attempting to filter out uninformative nodes based on my criteria so as to render less number of nodes than the actual data. (I know i will run into performance issues with larger trees). Any help would be much appreciated.
NOTE: When I say canvas, I mean the area on which the tree is drawn and not the "canvas". I am not familiar with the jargon so kindly read accordingly.
Hope this helps someone.
I faced similar problems also using the flare tree code as a base for what I was building and the suggested links did not seem to account for a lot of variance in node structure? I have many trees to display with a dynamic number of nodes and structuring. This solution worked for me:
Concerning height: After observing the translate offsets per node, I learned that d.x (vs d.y, as tree is flipped) is an offset from the root node, with the nodes above root going negative and those below going positive. So, I "calculated" the max offset in both directions each time a node is appended, then with that information, adjusted the canvas height and the view translation (starting point of root).
For width: max d.depth * by the (y length normalization the code uses) + margins
let aboveBount = 0
let belowBound = 0
let maxDepth = 0
nodeEnter.each( (d) => {
if( Math.sign(d.x) === -1 && d.x < boundAbove) {
boundAbove = d.x
}
if( Math.sign(d.x) === 1 && d.x > boundBelow) {
boundBelow = d.x
}
if( d.depth > maxDepth){
maxDepth = d.depth
}
})
const newHeight = boundBelow + Math.abs(boundAbove) + nodeHeight*2 + margin.top*2
svg.style('height', newHeight)
svg.style('width'. maxDepth*180 + margin.left*2)
//180 was the amount set to normailze path length
svg.attr('transform', `translate(${margin.left}, ${Math.abs(boundAbove) + margin.top})`)
Well, best wishes and happy coding!
I was facing the similar problem and now I have find out a solution. Check on this link. D3 collapsible tree, node merging issue
I was wondering if there is a way to create a force directed layout with d3.js and restrict it by an arbitrary shape in such a way that
all the nodes are equivalently distributed within the shape and
the distance between the border and the nodes is equally to the distance between the nodes
I hope there is already such a solution out there. Otherwise my idea is to start with the force directed layout and check the distances from the nodes to the borders in each iteration. Any suggestions from yourside?
Your idea is mine too. In the tick function you could add additional forces. This is my suggestion (not tested):
force.on('tick', function(e) {
node
.each(calcBorderDistance)
.attr('transform', function(d) {
d.x -= e.alpha*(1/Math.pow(d.borderDistance.x,2);
d.y -= e.alpha*(1/Math.pow(d.borderDistance.y,2);
return 'translate(' + d.x + ',' + d.y + ')'; // Move node
});
});
function calcBorderdistance(d) {
// Insert code here to calculate the distance to the nearest border of your shape
var x = ..., y = ...;
d.borderDistance = {'x':x,'y':y};
}
I have the inverse quadratic distance to the nearest border function loosely based on the formulas in excelent paper Drawing Graphs Nicely using Simulated Annealing. Following picture illustrates how methods from this paper affect drawing nodes bounded by a box:
And this picture illustrate case with different constraints, involving links between nodes: