Is it possible to specify rangePoints to handle circles of different sizes so that the distances are calculated by their edges rather than their centers?
For example, this is what I am getting:
() represent circle edges; <----> represents distance calculated by rangePoints
( <----)---(-><-)-------(-> )
^Notice how it looks like the middle circle is closer to the left-most circle. Instead, I'd like to see the following:
( )<---->( )<---->( )
The function I am using looks something like:
var y = d3.scale.ordinal()
.domain(data.map(function(d) { return d.value}))
.rangePoints([0, width]);
var item = chart.append("g")
.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("cy", function(d) { return y(d.value); })
As #LarsKotthoff mentioned, you're going to need a custom scale implementation to do this.
This is going to be somewhat complex in this case, because the scale needs to take into account not only the number of elements in the domain, but also what their exact values are. Basically, when calculating the position of each element, your scale will need to take into account the space taken up by each element preceding it, and also include a spacer based on a division of the total space.
Here's what it would have to do:
First, in setting up the scale you need to do the following:
Find the total distance spanned by the output range
Find the sum of the diameters of each element in the domain
Take the difference of these to find the remaining space available
Divide the remaining space by the number of spaces (number of elements minus one)
This will give you a value for the space needed between each circle.
Then for each element:
Find the sum of the diameters of the preceding circles
Multiply the spacer value by the number of preceding circles
Add the sum of these to the radius of the current circle
Because of this, your scale will need to be based on the index as well as the datum.
Here is a pretty crude implementation that assumes the domain is an array of radii and the range is the endpoints of your output:
var customPointScale = function() {
var domain,
range;
// returned scale fn takes datum and index
function scale(d,i) {
var n = domain.length,
totalSpan = range[1] - range[0],
// loop over the domain to find the sum of the diameters
sumDiameters = (function(){
var output = 0;
for (var a = 0; a < n; a++) {
// add radius * 2 to get diameter
output += domain[a] * 2;
}
return output;
})(),
remainingSpace = totalSpan - sumDiameters,
// there is one fewer space than the number of elements
spacer = remainingSpace / (n-1);
// loop over the elements that came before to find the distance spanned
var distanceSoFar = (function() {
var output = 0;
for(var a = 0; a < i; a++) {
// diameter + spacer, for each element traversed
output += (domain[a] * 2) + spacer;
}
return output;
})();
// return the radius plus the distance traversed so far
return d + distanceSoFar;
}
scale.domain = function(_) {
if (!arguments.length) return domain;
domain = _;
return scale;
};
scale.range = function(_) {
if (!arguments.length) return range;
range = _;
return scale;
};
return scale;
};
Here's a JSBin that uses this implementation with some example data. Hope that helps.
Related
I'm working on an AE project where around 50 Emojis should have a drop shadow on the floor.To make things easier I tried to add an expression that auto shrinks and grows the shadows based on the distance of the emoji to the floor.
Here is what I've tried
Drop Shadow Approach
You can see that the shadow grows and shrinks but in the wrong direction. So when emoji comes closer to the floor it shrinks and when the distance is more it grows. I need the opposite of the current behavior.
How do I achieve that?
This is the expression I've used for the scale property of the shadow layer. Shadow layer is separate from the emoji layer. So I have a composition with only 2 layers.
var y = thisComp.layer("smile").position[1];
var dist = Math.sqrt( Math.pow((this.position[0]-this.position[0]), 2) + Math.pow((this.position[1]-y), 2) );
newValue = dist ;
xScale = newValue;
yScale = newValue;
[xScale,yScale]
Thanks for your time.
The basic concept here is mapping values from one range to another. You want to say that (for example) as the distance changes between 0 and 100, the scale should change proportionally between 1 and 0.
function map ( x, oldMin, oldMax, newMin, newMax ) {
return newMin + ( x - oldMin ) / ( oldMax - oldMin ) * ( newMax - newMin );
}
var minDistance = 0;
var maxDistance = 100;
var maxScale = 1;
var minScale = 0;
xScale = yScale = map( dist, minDistance, maxDistance, maxScale, minScale );
I've created a pinch filter/effect on canvas using the following algorithm:
// iterate pixels
for (var i = 0; i < originalPixels.data.length; i+= 4) {
// calculate a pixel's position, distance, and angle
var pixel = new Pixel(affectedPixels, i, origin);
// check if the pixel is in the effect area
if (pixel.dist < effectRadius) {
// initial method (flawed)
// iterate original pixels and calculate the new position of the current pixel in the affected pixels
if (method.value == "org2aff") {
var targetDist = ( pixel.dist - (1 - pixel.dist / effectRadius) * (effectStrength * effectRadius) ).clamp(0, effectRadius);
var targetPos = calcPos(origin, pixel.angle, targetDist);
setPixel(affectedPixels, targetPos.x, targetPos.y, getPixel(originalPixels, pixel.pos.x, pixel.pos.y));
} else {
// alternative method (better)
// iterate affected pixels and calculate the original position of the current pixel in the original pixels
var originalDist = (pixel.dist + (effectStrength * effectRadius)) / (1 + effectStrength);
var originalPos = calcPos(origin, pixel.angle, originalDist);
setPixel(affectedPixels, pixel.pos.x, pixel.pos.y, getPixel(originalPixels, originalPos.x, originalPos.y));
}
} else {
// copy unaffected pixels from original to new image
setPixel(affectedPixels, pixel.pos.x, pixel.pos.y, getPixel(originalPixels, pixel.pos.x, pixel.pos.y));
}
}
I've struggled a lot to get it to this point and I'm quite happy with the result. Nevertheless, I have a small problem; jagged pixels. Compare the JS pinch with Gimp's:
I don't know what I'm missing. Do I need to apply another filter after the actual filter? Or is my algorithm wrong altogether?
I can't add the full code here (as a SO snippet) because it contains 4 base64 images/textures (65k chars in total). Instead, here's a JSFiddle.
One way to clean up the result is supersampling. Here's a simple example: https://jsfiddle.net/Lawmo4q8/
Basically, instead of calculating a single value for a single pixel, you take multiple value samples within/around the pixel...
let color =
calcColor(x - 0.25, y - 0.25) + calcColor(x + 0.25, y - 0.25) +
calcColor(x - 0.25, y + 0.25) + calcColor(x + 0.25, y + 0.25);
...and merge the results in some way.
color /= 4;
I display a line chart with D3 with roughly the following code (given the scale functions x, y and the float array data):
var line = d3.svg.line()
.interpolate("basis")
.x(function (d, i) { return x(i); })
.y(function (d) { return y(d); });
d3.select('.line').attr('d', line(data));
Now I want to know the vertical height of the line at a given horizontal pixel position. The data array has lesser data points than pixels and the displayed line is interpolated, so it is not straight-forward to deduce the height of the line at a given pixel just from the data array.
Any hints?
This solution is much more efficient than the accepted answer. It's execution time is logarithmic (while accepted answer has linear complexity).
var findYatXbyBisection = function(x, path, error){
var length_end = path.getTotalLength()
, length_start = 0
, point = path.getPointAtLength((length_end + length_start) / 2) // get the middle point
, bisection_iterations_max = 50
, bisection_iterations = 0
error = error || 0.01
while (x < point.x - error || x > point.x + error) {
// get the middle point
point = path.getPointAtLength((length_end + length_start) / 2)
if (x < point.x) {
length_end = (length_start + length_end)/2
} else {
length_start = (length_start + length_end)/2
}
// Increase iteration
if(bisection_iterations_max < ++ bisection_iterations)
break;
}
return point.y
}
Edited 19-Sep-2012 per comments with many thanks to nrabinowitz!
You will need to do some sort of search of the data returned by getPointAtLength. (See https://developer.mozilla.org/en-US/docs/DOM/SVGPathElement.)
// Line
var line = d3.svg.line()
.interpolate("basis")
.x(function (d) { return i; })
.y(function(d, i) { return 100*Math.sin(i) + 100; });
// Append the path to the DOM
d3.select("svg#chart") //or whatever your SVG container is
.append("svg:path")
.attr("d", line([0,10,20,30,40,50,60,70,80,90,100]))
.attr("id", "myline");
// Get the coordinates
function findYatX(x, linePath) {
function getXY(len) {
var point = linePath.getPointAtLength(len);
return [point.x, point.y];
}
var curlen = 0;
while (getXY(curlen)[0] < x) { curlen += 0.01; }
return getXY(curlen);
}
console.log(findYatX(5, document.getElementById("myline")));
For me this returns [5.000403881072998, 140.6229248046875].
This search function, findYatX, is far from efficient (runs in O(n) time), but illustrates the point.
I have tried implementing findYatXbisection (as nicely suggested by bumbu), and I could not get it to work AS IS.
Instead of modifying the length as a function of length_end and length_start, I just decreased the length by 50% (if x < point.x) or increased by 50% (if x> point.x) but always relative to start length of zero. I have also incorporated revXscale/revYscale to convert pixels to x/y values as set by my d3.scale functions.
function findYatX(x,path,error){
var length = apath.getTotalLength()
, point = path.getPointAtLength(length)
, bisection_iterations_max=50
, bisection_iterations = 0
error = error || 0.1
while (x < revXscale(point.x) -error || x> revXscale(point.x + error) {
point = path.getPointAtlength(length)
if (x < revXscale(point.x)) {
length = length/2
} else {
length = 3/2*length
}
if (bisection_iterations_max < ++ bisection_iterations) {
break;
}
}
return revYscale(point.y)
}
I'm using d3 tree layout similar to this example: http://bl.ocks.org/mbostock/4339083
I implemented a search box that when typing, centers your screen on a virtual "average" position of all the appropriate nodes.
I want to adjust the scale, so that selected nodes will be
All Visible
As zoomed in as possible.
If the search match is exactly 1, simulate the clicking on the node, else center to this virtual position.
if (matches[0].length === 1) {
click(matches.datum(), 0, 0, false);
}
else {
var position = GetAveragePosition(matches);
centerToPosition(position.x, position.y, 1);
}
This is what the centerToPosition function looks like:
function centerToPosition(x0, y0, newScale) {
if (typeof newScale == "undefined") {
scale = zoomListener.scale();
}
else {
scale = newScale;
}
var x = y0 * -1; //not sure why this is.. but it is
var y = x0 * -1;
x = x * scale + viewerWidth / 2;
y = y * scale + viewerHeight / 2;
d3.select('g').transition()
.duration(duration)
.attr("transform", "translate(" + x + "," + y + ")scale(" + scale + ")");
zoomListener.scale(scale);
zoomListener.translate([x, y]);
}
So how can I calculate the new scale? I tried different variations by taking the extents of the data points
var xExtent = d3.extent(matches.data(), function (d) {
return d.x0;
});
var yExtent = d3.extent(matches.data(), function (d) {
return d.y0;
});
Also tried looking at the transform properties of the group before centering the screen.
var components = d3.transform(svgGroup.attr("transform"));
I'll try to add a js fiddle soon!
EDIT: Here it is: http://jsfiddle.net/7SJqC/
Interesting project.
The method of determining the appropriate scale to fit a collection of points is fairly straightforward, although it took me quite a while to figure out why it wasn't working for me -- I hadn't clued in to the fact that (since you were drawing the tree horizontally) "x" from the tree layout represented vertical position, and "y" represented horizontal position, so I was getting apparently arbitrary results.
With that cleared up, to figure out the zoom you simply need to find the height and width (in data-coordinates) of the area you want to display, and compare that with the height and width of the viewport (or whatever your original max and min dimensions are).
ScaleFactor = oldDomain / newDomain
Generally, you don't want to distort the image with different horizontal and vertical scales, so you figure out the scale factor separately for width and height and take the minimum (so the entire area will fit in the viewport).
You can use the d3 array functions to figure out the extent of positions in each direction, and then find the middle of the extent adding max and min and dividing by two.
var matches = d3.selectAll(".selected");
/*...*/
if ( matches.empty() ) {
centerToPosition(0, 0, 1); //reset
}
else if (matches.size() === 1) {
click(matches.datum(), 0, 0, false);
}
else {
var xExtent = d3.extent(matches.data(), function (d) {
return d.x0;
});
var yExtent = d3.extent(matches.data(), function (d) {
return d.y0;
});
//note: the "x" values are used to set VERTICAL position,
//while the "y" values are setting the HORIZONTAL position
var potentialXZoom = viewerHeight/(xExtent[1] - xExtent[0] + 20);
var potentialYZoom = viewerWidth/(yExtent[1] - yExtent[0] + 150);
//The "20" and "150" are for height and width of the labels
//You could (should) replace with calculated values
//or values stored in variables
centerToPosition( (xExtent[0] + xExtent[1])/2,
(yExtent[0] + yExtent[1])/2,
Math.min(potentialXZoom, potentialYZoom)
);
}
http://jsfiddle.net/7SJqC/2/
I display a line chart with D3 with roughly the following code (given the scale functions x, y and the float array data):
var line = d3.svg.line()
.interpolate("basis")
.x(function (d, i) { return x(i); })
.y(function (d) { return y(d); });
d3.select('.line').attr('d', line(data));
Now I want to know the vertical height of the line at a given horizontal pixel position. The data array has lesser data points than pixels and the displayed line is interpolated, so it is not straight-forward to deduce the height of the line at a given pixel just from the data array.
Any hints?
This solution is much more efficient than the accepted answer. It's execution time is logarithmic (while accepted answer has linear complexity).
var findYatXbyBisection = function(x, path, error){
var length_end = path.getTotalLength()
, length_start = 0
, point = path.getPointAtLength((length_end + length_start) / 2) // get the middle point
, bisection_iterations_max = 50
, bisection_iterations = 0
error = error || 0.01
while (x < point.x - error || x > point.x + error) {
// get the middle point
point = path.getPointAtLength((length_end + length_start) / 2)
if (x < point.x) {
length_end = (length_start + length_end)/2
} else {
length_start = (length_start + length_end)/2
}
// Increase iteration
if(bisection_iterations_max < ++ bisection_iterations)
break;
}
return point.y
}
Edited 19-Sep-2012 per comments with many thanks to nrabinowitz!
You will need to do some sort of search of the data returned by getPointAtLength. (See https://developer.mozilla.org/en-US/docs/DOM/SVGPathElement.)
// Line
var line = d3.svg.line()
.interpolate("basis")
.x(function (d) { return i; })
.y(function(d, i) { return 100*Math.sin(i) + 100; });
// Append the path to the DOM
d3.select("svg#chart") //or whatever your SVG container is
.append("svg:path")
.attr("d", line([0,10,20,30,40,50,60,70,80,90,100]))
.attr("id", "myline");
// Get the coordinates
function findYatX(x, linePath) {
function getXY(len) {
var point = linePath.getPointAtLength(len);
return [point.x, point.y];
}
var curlen = 0;
while (getXY(curlen)[0] < x) { curlen += 0.01; }
return getXY(curlen);
}
console.log(findYatX(5, document.getElementById("myline")));
For me this returns [5.000403881072998, 140.6229248046875].
This search function, findYatX, is far from efficient (runs in O(n) time), but illustrates the point.
I have tried implementing findYatXbisection (as nicely suggested by bumbu), and I could not get it to work AS IS.
Instead of modifying the length as a function of length_end and length_start, I just decreased the length by 50% (if x < point.x) or increased by 50% (if x> point.x) but always relative to start length of zero. I have also incorporated revXscale/revYscale to convert pixels to x/y values as set by my d3.scale functions.
function findYatX(x,path,error){
var length = apath.getTotalLength()
, point = path.getPointAtLength(length)
, bisection_iterations_max=50
, bisection_iterations = 0
error = error || 0.1
while (x < revXscale(point.x) -error || x> revXscale(point.x + error) {
point = path.getPointAtlength(length)
if (x < revXscale(point.x)) {
length = length/2
} else {
length = 3/2*length
}
if (bisection_iterations_max < ++ bisection_iterations) {
break;
}
}
return revYscale(point.y)
}