Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3: refining ordinal scale to return groups of colours?

I have set up an ordinal scale in D3.js as follows, and it works well so far:

var color = d3.scale.ordinal().range([ 'blue', 'red', 'green' ]); 
color.domain();  
console.log(color(0)); // returns 'blue'

However, what I'd really like to do is be able to pass two numbers into the scale, and have it return a particular sub-shade of blue, red or green - the primary shade depending on the first number, the sub-shade depending on the second number.

Perhaps I can combine d3.scale.ordinal() with d3.interpolateRgb() in some way to do this? I'm not sure if interpolateRgb is the right choice though, because matters that the colours are consistent, depending on the input numbers.

So this is what I'd like to achieve:

color(0, 256); // return a shade of blue
color(0, 257); // return a second shade of blue
color(0, 256); // return the first shade of blue again

Any ideas for achieving this in D3? Thank you for your help.

like image 515
Richard Avatar asked Apr 30 '12 21:04

Richard


1 Answers

you could consider something like this:

var colorgroup = d3.scale.ordinal()
    .domain(d3.range(3))
    .range([ 'blue', 'red', 'green' ]); 
var brightrange = d3.scale.linear()
    .domain([0,300])
    .range([0,3]);  
function color(group,shift) {
     if (shift >= 0) {return d3.hsl(colorgroup(group)).darker(brightrange(shift));}
     else {return d3.hsl(colorgroup(group)).brighter(brightrange(-shift));}             
} 

examples:

console.log(color(0,255)); //dark blue
console.log(color(0,0)); //med blue
console.log(color(0,-150)); //light blue
like image 75
Josh Avatar answered Sep 25 '22 22:09

Josh