I want to create a chart with scale break on y axis. I don't want to use a non-linear scale but using a scale break make lower values more visible when having data anomalies. What is the best way to implement that in nvd3 or in general in d3?
Lacking other options I created a brute force solution, manipulating the vertical <path>
of the Y axis.
Using pseudo code, you use it like this:
var domainPath = yAxis
.select('path.domain');
domainPath.attr('d', breakScale(domainPath.attr('d'), 14, 6, 4, 7);
The breakScale function is not very special nor elegant, but here it goes:
function breakScale(pathString, amplitude, wavelength, periods, dist){
var parts = pathString.match(/(.*)(H-\d+)/);
var first = parts[1];
var last = parts[2];
first = first.replace(/(.*?V)(\d+)/, function(match, p1, p2) { return p1 + (p2-dist-(wavelength)*periods) });
var newPath = first;
for(var i=0; i<periods+1; i++){
if(i === 0){
newPath += 'l-' + (amplitude/2) + ',' + (wavelength/2);
}
else if(i == periods){
newPath += 'l' + (i%2?'':'-') + (amplitude/2) + ',' + (wavelength/2);
}
else {
newPath += 'l' + (i%2?'':'-') + amplitude + ',' + wavelength;
}
}
newPath += 'v' + dist + last;
return newPath;
}
dist
defines the distance from the start of the axis that the wavy thing should begin. The function probably works best with even numbers for amplitude
and wavelength
because they are both halved for the first and last part of the wave. periods
should be at least 3.
Given a typical domain axis path string like M-6,0H0V376H-6
, it will spit back something like M-6,0H0V345l-7,3l14,6l-14,6l14,6l-7,3v7H-6
which would look like this:
来源:https://stackoverflow.com/questions/20249054/nvd3-js-d3-js-scale-break