admin管理员组

文章数量:1279246

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 bine 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.

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 bine 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.

Share Improve this question edited May 3, 2012 at 19:38 ZachB 15.4k5 gold badges66 silver badges93 bronze badges asked Apr 30, 2012 at 21:41 RichardRichard 32.9k30 gold badges111 silver badges146 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 14

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

本文标签: javascriptD3 refining ordinal scale to return groups of coloursStack Overflow