Skip to content

Instantly share code, notes, and snippets.

@john-guerra
Last active September 28, 2017 23:44
Show Gist options
  • Save john-guerra/a75733ba5767813d4f31026d1d5e6244 to your computer and use it in GitHub Desktop.
Save john-guerra/a75733ba5767813d4f31026d1d5e6244 to your computer and use it in GitHub Desktop.
Discrete vs continuous sequential scales with d3-scale-chromatic
license: mit
<!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([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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment