Skip to content

Instantly share code, notes, and snippets.

@enthal
Last active November 14, 2020 02:55
Show Gist options
  • Select an option

  • Save enthal/060290a72e8c29d9f160 to your computer and use it in GitHub Desktop.

Select an option

Save enthal/060290a72e8c29d9f160 to your computer and use it in GitHub Desktop.
series normalization per mouse-x (D3.js): https://bl.ocks.org/enthal/060290a72e8c29d9f160
<!DOCTYPE html>
<meta charset="utf-8">
<style>
svg .chart {
fill: none;
stroke: #000;
stroke-width: 2px;
}
svg rect.mouse {
fill: none;
pointer-events: all;
}
</style>
<body></body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
<script>
var n=100, seriesList = [];
pushSeries(function(i) { return Math.sin(i*Math.PI/(n*0.2))+2; });
pushSeries(function(i) { return Math.cos(i*Math.PI/(n*0.3))+2; });
pushSeries(function(i) { return Math.cos(i*Math.PI/(n*0.15))/2+3*i/n+2; });
pushSeries(function(i) { return Math.pow(i/n,1.8)+1; });
var width = 960,
height = 500;
var x = d3.scale.linear().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
var series = seriesList[0];
x.domain([0, n]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var chart = svg.append('g').classed('chart', true);
effectScaledPaths(0);
svg.append("rect").classed("mouse", true)
.attr("width", width)
.attr("height", height)
.on("mousemove", mousemove);
// var lastX0;
function pushSeries(fn) {
var s = [];
seriesList.push(s);
for (var i=0;i<n;i++) { s.push(fn(i)); }
}
function mousemove() {
effectScaledPaths(Math.floor(x.invert(d3.mouse(this)[0]))); // TODO: bisect when x domain isn't index?
}
function effectScaledPaths(x0) {
/*
Scale each series to be proportional to its value at x0,
such that all series cross at some single point at mouse.x,
setting y.domain to extent of extents of all so-scaled series (i.e., global max,min).
*/
var ss = seriesList.slice();
var extents = [];
for (var ssi in ss) {
var s = ss[ssi] = ss[ssi].slice();
var factor = 1.0 / s[x0]; // but nothing is proportional to a value of 0
for (var si in s) {
s[si] *= factor;
}
extents.push(d3.extent(s));
}
y.domain(d3.extent(d3.merge(extents)));
var updateSel = chart.selectAll('path.series').data(ss);
updateSel.enter().append('path').classed('series', true)
updateSel
.attr("stroke", d3.scale.category10())
.transition()
.duration(70)
.ease("linear")
.attr('d', d3.svg.line()
// .interpolate('basis')
.x(function(d,i) { return x(i); })
.y(y) );
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment