Created
August 8, 2019 18:24
-
-
Save connerxyz/4bb11bd3629947fe52ee7dd96b467e63 to your computer and use it in GitHub Desktop.
d3.js: v5: mapping dynamic sets of discrete values to continuous color ranges
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// An array of discrete values (possibly dynamically generated) | |
var discreteValues = ['John', 'Jack', 'Jill', 'Jane', 'Jim', 'Joan']; | |
// 1st scale establishes relationship between continuous [0,1] and | |
// the array index of the discrete values | |
var preColor = d3.scaleLinear() | |
.domain([0, discreteValues.length - 1]) | |
.range([0, 1]); | |
console.log(preColor(discreteValues.indexOf('John'))) // 0 | |
console.log(preColor(discreteValues.indexOf('Jack'))) // 0.2 | |
console.log(preColor(discreteValues.indexOf('Joan'))) // 1.0 | |
// 2nd scale relates a discrete entity name index to a color via the 1st | |
// scale. We get a continuous value from the entity index going into the 1st | |
// scale, that continuous value is then mapped to a color using the 2nd scale | |
var color = i => { return d3.scaleSequential(d3.interpolateRainbow)(preColor(i)); }; | |
console.log(color(discreteValues.indexOf('John'))) // rgb(110, 64, 170) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment