How to zoom via brush in d3 with non-standart axises - javascript

Im trying to do the zooming via brush like in this block
https://bl.ocks.org/FrissAnalytics/539a46e17640613ebeb94598aad0c92d
The difference is that I need to define axis values manually due to zooming, cause I need to keep the distance between ticks the same (like scaleOrdinal, but I did it with scaleLinear).
Im stuck with the brushing - it works fine when it zoom via brush first time, but if I want to go deeper, the zoom is lagging - the scale is calculating well, but translation goes at any place, but not at right.
There is my fiddle (it is a bit messy, I called getRange several times for defining boundaries)
https://jsfiddle.net/Celeritas/y2u06kpm/2/
So I have this code now for brush_end event
function brush_endEvent() {
const s = d3.event.selection;
if (!s && lastSelection !== null) {
//this doing the same thing
let scaleX = lastTransform.rescaleX(x);
let scaleY = lastTransform.rescaleY(y);
gxAxis.call(xAxis.scale(scaleX));
gyAxis.call(yAxis.scale(scaleY));
//here I getting the current domain for zoomed area, which will set with the equal distance between ticks
getRange({
x1: scaleX.domain()[0],
x2: scaleX.domain()[scaleX.domain().length - 1],
y1: scaleY.domain()[0],
y2: scaleY.domain()[scaleY.domain().length - 1],
})
let kWidth = Math.ceil(tickTextWidth / (width / t.length)) + 1
let kHeight = Math.ceil(tickTextHeight / (height / b.length))
//im redefining domains manually
scaleX.domain(t)
scaleY.domain(b)
xAxis.tickValues(t.filter((e, i) => i % kWidth === 0)).tickFormat(d3.format('d'))
yAxis.tickValues(b.filter((e, i) => i % kHeight === 0)).tickFormat(d3.format('d'))
xAxis2.tickValues(t.filter((e, i) => i % kWidth === 0)).tickFormat(d3.format('d'))
yAxis2.tickValues(b.filter((e, i) => i % kHeight === 0)).tickFormat(d3.format('d'))
let totalX = Math.abs(lastSelection.x2 - lastSelection.x1);
const originalPoint = [scaleX.invert(lastSelection.x1), scaleY.invert(lastSelection.y1)];
const tt = d3.zoomIdentity.scale(((width * lastTransform.k) / totalX));
// BUT HERE im not doing rescale, cause im already redefine domain earlier
//scaleX = tt.rescaleX(x);
//scaleY = tt.rescaleY(y);
canvasChart
.transition()
.duration(200)
.ease(d3.easeLinear)
.call(zoom_function.transform,
d3.zoomIdentity
.translate(scaleX(originalPoint[0]) * -1, scaleY(originalPoint[1]) * -1)
.scale(tt.k));
lastSelection = null;
} else {
brushSvg.call(brush.move, null);
}
}
So Im in despair, I dont getting, how to set zoom to the right position after brushing.
Thanks for any help!

d3.zoomIdentity
.translate(x(originalPoint[0]) * -1, y(originalPoint[1]) * -1)
.scale(tt.k)
Well, the mistake was in the x-y for zoom. It should be original, non-rescaled domain

Related

Accurate pan and zoom to svg node

I am trying to pan and zoom to a svg node using d3js. But I cannot get my head around the math here.
If I force the desired zoom level to be 1, then I seem to get it right.
Here's an example:
let svg = d3.select('svg'),
svgW = svg.node().getBoundingClientRect().width,
svgH = svg.node().getBoundingClientRect().height,
svgCentroid = {
x : svgW / 2,
y : svgH / 2
};
// zoom functionality has been applied to this one
let selector = d3.select('#container');
let elem = d3.select('[id="6"]'),
elemBounds = elem.node().getBBox(),
elemCentroid = {
x : elemBounds.x + (elemBounds.width / 2),
y : elemBounds.y + (elemBounds.height / 2)
};
let position = {
x : svgCentroid.x - elemCentroid.x,
y : svgCentroid.y - elemCentroid.y
};
selector.transition()
.duration(750)
.call(this.zoom.transform, d3.zoomIdentity
.translate(position.x, position.y)
// set scale to 1
.scale(1)
);
My first naive thought was "piece of cake". I will just multiply the calculated positions with desired zoom level. But, surprise surprise, that got me terribly wrong.
// failed miserably
selector.transition()
.duration(750)
.call(this.zoom.transform, d3.zoomIdentity
.translate(position.x * 5, position.y * 5)
.scale(5)
);
I've been trying to play around with this example:
https://bl.ocks.org/smithant/664d6cf86e53442d09687b154a9a411d
It pretty much sums up my intentions, but even though it's right there I don't fully understand it and thus it does not work properly with the rest of my code. I guess what confuses me most about this particular example are how the variables have their names declared.
I'd be grateful if someone could point me in the right direction here. How can I achieve this? What is the appropriate math to correctly zoom and pan within an SVG?
Thanks :)
I think that what you're looking for is:
function () {
var t = d3.transform(d3.select(this).attr("transform")),
x = t.translate[0],
y = t.translate[1];
var scale = 10;
svg.transition().duration(3000)
.call(zoom.translate([((x * -scale) + (svgWidth / 2)), ((y * -scale) + svgHeight / 2)])
.scale(scale).event);
}
Where this represents the element. Have a look here for a working example. In the example you'll be able to zoom to element after pressing on it. Also if panning and zooming an svg is all you need to do check out this library. It just works, no maths required :).

JS randomly distribute child elements in their parent without overlap

I am trying to make something where a bunch of circles (divs with border-radius) can be dynamically generated and laid out in their container without overlapping.
Here is my progress so far - https://jsbin.com/domogivuse/2/edit?html,css,js,output
var sizes = [200, 120, 500, 80, 145];
var max = sizes.reduce(function(a, b) {
return Math.max(a, b);
});
var min = sizes.reduce(function(a, b) {
return Math.min(a, b);
});
var percentages = sizes.map(function(x) {
return ((x - min) * 100) / (max - min);
});
percentages.sort(function(a, b) {
return b-a;
})
var container = document.getElementById('container');
var width = container.clientWidth;
var height = container.clientHeight;
var area = width * height;
var maxCircleArea = (area / sizes.length);
var pi = Math.PI;
var maxRadius = Math.sqrt(maxCircleArea / pi);
var minRadius = maxRadius * 0.50;
var range = maxRadius - minRadius;
var radii = percentages.map(function(x) {
return ((x / 100) * range) + minRadius;
});
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
var coords = [];
radii.forEach(function(e, i) {
var circle = document.createElement('div');
var randomTop = getRandomArbitrary(0, height);
var randomLeft = getRandomArbitrary(0, width);
var top = randomTop + (e * 2) < height ?
randomTop :
randomTop - (e * 2) >= 0 ?
randomTop - (e * 2) :
randomTop - e;
var left = randomLeft + (e * 2) < width ?
randomLeft :
randomLeft - (e * 2) >= 0 ?
randomLeft - (e * 2) :
randomLeft - e;
var x = left + e;
var y = top + e;
coords.push({x: x, y: y, radius: e});
circle.className = 'bubble';
circle.style.width = e * 2 + 'px';
circle.style.height = e * 2 + 'px';
circle.style.top = top + 'px';
circle.style.left = left + 'px';
circle.innerText = i
container.appendChild(circle);
});
I have got them being added to the parent container but as you can see they overlap and I don't really know how to solve this. I tried implementing a formula like (x1 - x2)^2 + (y1 - y2)^2 < (radius1 + radius2)^2 but I have no idea about this.
Any help appreciated.
What you're trying to do is called "Packing" and is actually a pretty hard problem. There are a couple potential approaches you can take here.
First, you can randomly distribute them (like you are currently doing), but including a "retry" test, in which if a circle overlaps another, you try a new location. Since it's possible to end up in an impossible situation, you would also want a retry limit at which point it gives up, goes back to the beginning, and tries randomly placing them again. This method is relatively easy, but has the down-side that you can't pack them very densely, because the chances of overlap become very very high. If maybe 1/3 of the total area is covered by circle, this could work.
Second, you can adjust the position of previously placed circles as you add more. This is more equivalent to how this would be accomplished physically -- as you add more you start having to shove the nearby ones out of the way in order to fit the new one. This will require not just finding the things that your current circle hits, but also the ones that would be hit if that one was to move. I would suggest something akin to a "springy" algorithm, where you randomly place all the circles (without thinking about if they fit), and then have a loop where you calculate overlap, and then exert a force on each circle based on that overlap (They push each other apart). This will push the circles away from each other until they stop overlapping. It will also support one circle pushing a second one into a third, and so on. This will be more complex to write, but will support much more dense configurations (since they can end up touching in the end). You still probably need a "this is impossible" check though, to keep it from getting stuck and looping forever.

d3.js version 4 - rect zoom - cannot get the transformation right

d3.js verison 4:
I have a line chart, which should have a rectangle zoom.
I used this example: http://bl.ocks.org/jasondavies/3689931
I don't want to apply the rectangle data to the scales, like in the example
Instead I want to apply this to my normal zoom Element.
For that I have the math:
.on("mouseup.zoomRect", function() {
d3.select(window).on("mousemove.zoomRect", null).on("mouseup.zoomRect", null);
d3.select("body").classed("noselect", false);
var m = d3.mouse(e);
m[0] = Math.max(0, Math.min(width, m[0]));
m[1] = Math.max(0, Math.min(height, m[1]));
if (m[0] !== origin[0] && m[1] !== origin[1]) {
//different code here
//I have the scale factor
var zoomRectWidth = Math.abs(m[0] - origin[0]);
scaleFactor = width / zoomRectWidth;
//Getting the translation
var translateX = Math.min(m[0], origin[0]);
//Apply to __zoom Element
var t = d3.zoomTransform(e.node());
e.transition()
.duration(that.chart.animationDuration)
.call(that.chart.zoomX.transform, t
.translate(translateX, 0)
.scale(scaleFactor)
.translate(-translateX, 0)
);
}
rect.remove();
refresh();
}, true);
So I actually get the scaleFactor right and it zooms in smoothly.
Only problem is, that I don't seem to get the translation correct.
So it zooms in to the wrong position.
So, now I got it right:
All transformations by earlier zooms need to be undone.
so that k = 1, x = 0, y = 0;
This is the d3.zoomIdentity.
From that point the current zoom needs to be applied and afterwards the translation.
After that the old transform needs to be applied, first translate and then scale
var t = d3.zoomTransform(e.node());
//store x translation
var x = t.x;
//store scaling factor
var k = t.k;
//apply first rect zoom scale and then translation
//then old translate and old zoom scale
e.transition()
.call(that.chart.zoomX.transform, d3.zoomIdentity
.scale(scaleFactor)
.translate(-translateX, 0)
.translate(x)
.scale(k)
);
Working Fiddle only for X-Axis here: https://jsfiddle.net/9j4kqq1v/3/
Working fiddle for X and Y-axis here: https://jsfiddle.net/9j4kqq1v/5/

d3.js spreading labels for pie charts

I'm using d3.js - I have a pie chart here. The problem though is when the slices are small - the labels overlap. What is the best way of spreading out the labels.
http://jsfiddle.net/BxLHd/16/
Here is the code for the labels. I am curious - is it possible to mock a 3d pie chart with d3?
//draw labels
valueLabels = label_group.selectAll("text.value").data(filteredData)
valueLabels.enter().append("svg:text")
.attr("class", "value")
.attr("transform", function(d) {
return "translate(" + Math.cos(((d.startAngle+d.endAngle - Math.PI)/2)) * (that.r + that.textOffset) + "," + Math.sin((d.startAngle+d.endAngle - Math.PI)/2) * (that.r + that.textOffset) + ")";
})
.attr("dy", function(d){
if ((d.startAngle+d.endAngle)/2 > Math.PI/2 && (d.startAngle+d.endAngle)/2 < Math.PI*1.5 ) {
return 5;
} else {
return -7;
}
})
.attr("text-anchor", function(d){
if ( (d.startAngle+d.endAngle)/2 < Math.PI ){
return "beginning";
} else {
return "end";
}
}).text(function(d){
//if value is greater than threshold show percentage
if(d.value > threshold){
var percentage = (d.value/that.totalOctets)*100;
return percentage.toFixed(2)+"%";
}
});
valueLabels.transition().duration(this.tweenDuration).attrTween("transform", this.textTween);
valueLabels.exit().remove();
As #The Old County discovered, the previous answer I posted fails in firefox because it relies on the SVG method .getIntersectionList() to find conflicts, and that method hasn't been implemented yet in Firefox.
That just means we have to keep track of label positions and test for conflicts ourselves. With d3, the most efficient way to check for layout conflicts involves using a quadtree data structure to store positions, that way you don't have to check every label for overlap, just those in a similar area of the visualization.
The second part of the code from the previous answer gets replaced with:
/* check whether the default position
overlaps any other labels*/
var conflicts = [];
labelLayout.visit(function(node, x1, y1, x2, y2){
//recurse down the tree, adding any overlapping labels
//to the conflicts array
//node is the node in the quadtree,
//node.point is the value that we added to the tree
//x1,y1,x2,y2 are the bounds of the rectangle that
//this node covers
if ( (x1 > d.r + maxLabelWidth/2)
//left edge of node is to the right of right edge of label
||(x2 < d.l - maxLabelWidth/2)
//right edge of node is to the left of left edge of label
||(y1 > d.b + maxLabelHeight/2)
//top (minY) edge of node is greater than the bottom of label
||(y2 < d.t - maxLabelHeight/2 ) )
//bottom (maxY) edge of node is less than the top of label
return true; //don't bother visiting children or checking this node
var p = node.point;
var v = false, h = false;
if ( p ) { //p is defined, i.e., there is a value stored in this node
h = ( ((p.l > d.l) && (p.l <= d.r))
|| ((p.r > d.l) && (p.r <= d.r))
|| ((p.l < d.l)&&(p.r >=d.r) ) ); //horizontal conflict
v = ( ((p.t > d.t) && (p.t <= d.b))
|| ((p.b > d.t) && (p.b <= d.b))
|| ((p.t < d.t)&&(p.b >=d.b) ) ); //vertical conflict
if (h&&v)
conflicts.push(p); //add to conflict list
}
});
if (conflicts.length) {
console.log(d, " conflicts with ", conflicts);
var rightEdge = d3.max(conflicts, function(d2) {
return d2.r;
});
d.l = rightEdge;
d.x = d.l + bbox.width / 2 + 5;
d.r = d.l + bbox.width + 10;
}
else console.log("no conflicts for ", d);
/* add this label to the quadtree, so it will show up as a conflict
for future labels. */
labelLayout.add( d );
var maxLabelWidth = Math.max(maxLabelWidth, bbox.width+10);
var maxLabelHeight = Math.max(maxLabelHeight, bbox.height+10);
Note that I've changed the parameter names for the edges of the label to l/r/b/t (left/right/bottom/top) to keep everything logical in my mind.
Live fiddle here: http://jsfiddle.net/Qh9X5/1249/
An added benefit of doing it this way is that you can check for conflicts based on the final position of the labels, before actually setting the position. Which means that you can use transitions for moving the labels into position after figuring out the positions for all the labels.
Should be possible to do. How exactly you want to do it will depend on what you want to do with spacing out the labels. There is not, however, a built in way of doing this.
The main problem with the labels is that, in your example, they rely on the same data for positioning that you are using for the slices of your pie chart. If you want them to space out more like excel does (i.e. give them room), you'll have to get creative. The information you have is their starting position, their height, and their width.
A really fun (my definition of fun) way to go about solving this would be to create a stochastic solver for an optimal arrangement of labels. You could do this with an energy-based method. Define an energy function where energy increases based on two criteria: distance from start point and overlap with nearby labels. You can do simple gradient descent based on that energy criteria to find a locally optimal solution with regards to your total energy, which would result in your labels being as close as possible to their original points without a significant amount of overlap, and without pushing more points away from their original points.
How much overlap is tolerable would depend on the energy function you specify, which should be tunable to give a good looking distribution of points. Similarly, how much you're willing to budge on point closeness would depend on the shape of your energy increase function for distance from the original point. (A linear energy increase will result in closer points, but greater outliers. A quadratic or a cubic will have greater average distance, but smaller outliers.)
There might also be an analytical way of solving for the minima, but that would be harder. You could probably develop a heuristic for positioning things, which is probably what excel does, but that would be less fun.
One way to check for conflicts is to use the <svg> element's getIntersectionList() method. That method requires you to pass in an SVGRect object (which is different from a <rect> element!), such as the object returned by a graphical element's .getBBox() method.
With those two methods, you can figure out where a label is within the screen and if it overlaps anything. However, one complication is that the rectangle coordinates passed to getIntersectionList are interpretted within the root SVG's coordinates, while the coordinates returned by getBBox are in the local coordinate system. So you also need the method getCTM() (get cumulative transformation matrix) to convert between the two.
I started with the example from Lars Khottof that #TheOldCounty had posted in a comment, as it already included lines between the arc segments and the labels. I did a little re-organization to put the labels, lines and arc segments in separate <g> elements. That avoids strange overlaps (arcs drawn on top of pointer lines) on update, and it also makes it easy to define which elements we're worried about overlapping -- other labels only, not the pointer lines or arcs -- by passing the parent <g> element as the second parameter to getIntersectionList.
The labels are positioned one at a time using an each function, and they have to be actually positioned (i.e., the attribute set to its final value, no transitions) at the time the position is calculated, so that they are in place when getIntersectionList is called for the next label's default position.
The decision of where to move a label if it overlaps a previous label is a complex one, as #ckersch's answer outlines. I keep it simple and just move it to the right of all the overlapped elements. This could cause a problem at the top of the pie, where labels from the last segments could be moved so that they overlap labels from the first segments, but that's unlikely if the pie chart is sorted by segment size.
Here's the key code:
labels.text(function (d) {
// Set the text *first*, so we can query the size
// of the label with .getBBox()
return d.value;
})
.each(function (d, i) {
// Move all calculations into the each function.
// Position values are stored in the data object
// so can be accessed later when drawing the line
/* calculate the position of the center marker */
var a = (d.startAngle + d.endAngle) / 2 ;
//trig functions adjusted to use the angle relative
//to the "12 o'clock" vector:
d.cx = Math.sin(a) * (that.radius - 75);
d.cy = -Math.cos(a) * (that.radius - 75);
/* calculate the default position for the label,
so that the middle of the label is centered in the arc*/
var bbox = this.getBBox();
//bbox.width and bbox.height will
//describe the size of the label text
var labelRadius = that.radius - 20;
d.x = Math.sin(a) * (labelRadius);
d.sx = d.x - bbox.width / 2 - 2;
d.ox = d.x + bbox.width / 2 + 2;
d.y = -Math.cos(a) * (that.radius - 20);
d.sy = d.oy = d.y + 5;
/* check whether the default position
overlaps any other labels*/
//adjust the bbox according to the default position
//AND the transform in effect
var matrix = this.getCTM();
bbox.x = d.x + matrix.e;
bbox.y = d.y + matrix.f;
var conflicts = this.ownerSVGElement
.getIntersectionList(bbox, this.parentNode);
/* clear conflicts */
if (conflicts.length) {
console.log("Conflict for ", d.data, conflicts);
var maxX = d3.max(conflicts, function(node) {
var bb = node.getBBox();
return bb.x + bb.width;
})
d.x = maxX + 13;
d.sx = d.x - bbox.width / 2 - 2;
d.ox = d.x + bbox.width / 2 + 2;
}
/* position this label, so it will show up as a conflict
for future labels. (Unfortunately, you can't use transitions.) */
d3.select(this)
.attr("x", function (d) {
return d.x;
})
.attr("y", function (d) {
return d.y;
});
});
And here's the working fiddle: http://jsfiddle.net/Qh9X5/1237/

D3 tree vertical separation

I am using the D3 tree layout, such as this one: http://mbostock.github.com/d3/talk/20111018/tree.html
I have modified it for my needs and am running into an issue. The example has the same issue too where if you have too many nodes open then they become compact and makes reading and interacting difficult. I am wanting to defined a minimum vertical space between nodes while re-sizing stage to allow for such spacing.
I tried modifying the separation algorithm to make it work:
.separation(function (a, b) {
return (a.parent == b.parent ? 1 : 2) / a.depth;
})
That didn't work. I also tried calculating which depth had the most children then telling the height of the stage to be children * spaceBetweenNodes. That got me closer, but still was not accurate.
depthCounts = [];
nodes.forEach(function(d, i) {
d.y = d.depth * 180;
if(!depthCounts[d.depth])
depthCounts[d.depth] = 0;
if(d.children)
{
depthCounts[d.depth] += d.children.length;
}
});
tree_resize(largest_depth(depthCounts) * spaceBetweenNodes);
I also tried to change the node's x value too in the method below where it calculates the y separation, but no cigar. I would post that change too but I removed it from my code.
nodes.forEach(function(d, i) {
d.y = d.depth * 180;
});
If you can suggest a way or know a way that I can accomplish a minimum spacing vertically between nodes please post. I will be very grateful. I am probably missing something very simple.
As of 2016, I was able to achieve this using just
tree.nodeSize([height, width])
https://github.com/mbostock/d3/wiki/Tree-Layout#nodeSize
The API Reference is a bit poor, but is works pretty straight forward. Be sure to use it after tree.size([height, width]) or else you will be overriding your values again.
For more reference: D3 Tree Layout Separation Between Nodes using NodeSize
I was able to figure this out with help from a user on Google Groups. I was not able to find the post. The solution requires you to modify D3.js in one spot, which is not recommended but it was the only to get around this issue that I could find.
Starting around line 5724 or this method: d3_layout_treeVisitAfter
change:
d3_layout_treeVisitAfter(root, function(node) {
node.x = (node.x - x0) / (x1 - x0) * size[0];
node.y = node.depth / y1 * size[1];
delete node._tree;
});
to:
d3_layout_treeVisitAfter(root, function(node) {
// make sure size is null, we will make it null when we create the tree
if(size === undefined || size == null)
{
node.x = (node.x - x0) * elementsize[0];
node.y = node.depth * elementsize[1];
}
else
{
node.x = (node.x - x0) / (x1 - x0) * size[0];
node.y = node.depth / y1 * size[1];
}
delete node._tree;
});
Below add a new variable called: elementsize and default it to [ 1, 1 ] to line 5731
var hierarchy = d3.layout.hierarchy().sort(null).value(null)
, separation = d3_layout_treeSeparation
, elementsize = [ 1, 1 ] // Right here
, size = [ 1, 1 ];
Below that there is a method called tree.size = function(x). Add the following below that definition:
tree.elementsize = function(x) {
if (!arguments.length) return elementsize;
elementsize = x;
return tree;
};
Finally when you create the tree you can change the elementsize like so
var tree = d3.layout.tree()
.size(null)
.elementsize(50, 240);
I know I'm not supposed to respond to other answers, but I don't have enough reputation to add a comment.
Anyway, I just wanted to update this for people using the latest d3.v3.js file. (I assume this is because of a new version, because the line references in the accepted answer were wrong for me.)
The d3.layout.tree function that you are editing is found between lines 6236 and 6345. d3_layout_treeVisitAfter starts on line 6318. The hierarchy variable is declared on line 6237. The bit about tree.elementsize still stands - I put it on line 6343.
Lastly (I assume this was an error): when you create the tree, put the dimensions inside square brackets, like you normally do with "size". So:
var tree = d3.layout.tree()
.size(null)
.elementsize([50, 240]);
The original fix you proposed will work, you just have to make sure you do it after you add everything to the canvas. d3 recalculates the layout each time you enter, exit, append, etc. Once you've done all that, then you can fiddle with the d.y to fix the depth.
nodes.forEach(function(d) { d.y = d.depth * fixdepth});

Categories