An example to ilustrate the difference of using d3.scaleThreshold vs d3.scaleSequential for creating discrete vs continuous diverging scales using d3.v4 and d3-scale-chromatic
See also sequential scales
Built with blockbuilder.org
| license: mit |
An example to ilustrate the difference of using d3.scaleThreshold vs d3.scaleSequential for creating discrete vs continuous diverging scales using d3.v4 and d3-scale-chromatic
See also sequential scales
Built with blockbuilder.org
| <!DOCTYPE html> | |
| <head> | |
| <meta charset="utf-8"> | |
| <script src="https://d3js.org/d3.v4.min.js"></script> | |
| <script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script> | |
| <style> | |
| body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } | |
| </style> | |
| </head> | |
| <body> | |
| <script> | |
| // Background canvas for quick drawing of 2k lines | |
| var canvas = d3.select("body").append("canvas") | |
| .attr("width", 960) | |
| .attr("height", 500); | |
| var ctx = canvas.node().getContext("2d"); | |
| //Translucent svg on top to show the axis | |
| var svg = d3.select("body").append("svg") | |
| .attr("width", 960) | |
| .attr("height", 500) | |
| .style("position", "fixed") | |
| .style("top", 0) | |
| .style("left", 0); | |
| var x = d3.scaleLinear().domain([-1, 1]).range([20, 500]); | |
| // Let's add an axis | |
| svg.append("g") | |
| .attr("class", "axis") | |
| .attr("transform", "translate(0, 50)") | |
| .call(d3.axisTop(x)); | |
| var steps = 5 | |
| //Discrete diverging scale | |
| var color_threshold = d3.scaleThreshold() | |
| .domain(d3.range(-1 + 2/steps, 1, 2/steps) ) //[-.6, -.2, .2, .6] | |
| .range(d3.schemePuOr[steps]); //=> 5 colors in an array | |
| //Continuous diverging scale | |
| var color_sequential = d3.scaleSequential(d3.interpolatePuOr) | |
| .domain([-1, 1]); | |
| // Let's draw 2000 lines on canvas for speed | |
| d3.range(-1, 1, 0.001) | |
| .forEach(function (d) { | |
| ctx.beginPath(); | |
| ctx.strokeStyle = color_threshold(d); | |
| ctx.moveTo(x(d), 50); | |
| ctx.lineTo(x(d), 70); | |
| ctx.stroke(); | |
| ctx.beginPath(); | |
| ctx.strokeStyle = color_sequential(d); | |
| ctx.moveTo(x(d), 80); | |
| ctx.lineTo(x(d), 100); | |
| ctx.stroke(); | |
| }); | |
| </script> | |
| </body> |