An example to ilustrate the difference of using d3.scaleThreshold vs d3.scaleSequential for creating discrete vs continuous sequential scales using d3.v4 and d3-scale-chromatic
Built with blockbuilder.org
forked from john-guerra's block: Discrete vs continuous diverging scales with d3-scale-chromatic
xxxxxxxxxx
<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([0, 100]).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 sequential scale
var color_threshold = d3.scaleThreshold()
.domain(d3.range(0+ 100/steps, 100, 100/steps) ) //[20, 40, 60, 80]
.range(d3.schemeGreens[steps]);
//Continuous sequential scale
var color_sequential = d3.scaleSequential(d3.interpolateGreens)
.domain([0,100]);
// Let's draw 1000 lines on canvas for speed
d3.range(0, 100, 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>
https://d3js.org/d3.v4.min.js
https://d3js.org/d3-scale-chromatic.v1.min.js