Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
D3 elastic scale closure
// a wrapper around d3's linear scale;
// extreme inputs (outside domain) push the domain while maintaining a fixed extent
function elasticScale() {
var sensitivity = 27,
origin = 0,
domain = [origin - sensitivity/2, origin + sensitivity/2],
scale = d3.scale.linear()
.domain(padDomain(domain))
.range([0, 0, 1, 1])
.clamp(true);
function eScale(theta) {
// the crux of it
if(theta < domain[0]) {
domain[0] = theta;
domain[1] = theta + sensitivity;
scale.domain(padDomain(domain));
} else if (theta > domain[1]) {
domain[1] = theta;
domain[0] = theta - sensitivity;
scale.domain(padDomain(domain));
}
return scale(theta);
}
eScale.sensitivity = function(value) {
if (!arguments.length) return sensitivity;
sensitivity = value;
domain = [origin - sensitivity/2, origin + sensitivity/2];
scale.domain(padDomain(domain));
return etScale;
};
function padDomain(domain) {
return [
domain[0],
domain[0] + (1/3) * (domain[1] - domain[0]),
domain[0] + (2/3) * (domain[1] - domain[0]),
domain[1]
];
}
return eScale;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment