3-color linear scale with anchor points
HTML
<div id="vis" style="height:800px;">
</div>
CSS
text {
font-family: sans-serif;
font-weight: normal;
font-size: 12px;
}
.q0-11{fill:rgb(255,0,0)}
.q1-11{fill:rgb(255,50,50)}
.q2-11{fill:rgb(255,100,100)}
.q3-11{fill:rgb(255,150,150)}
.q4-11{fill:rgb(255,200,200)}
.q5-11{fill:rgb(255,255,255)}
.q6-11{fill:rgb(200,255,200)}
.q7-11{fill:rgb(150,255,150)}
.q8-11{fill:rgb(100,255,100)}
.q9-11{fill:rgb(50,255,50)}
.q10-11{fill:rgb(0,255,0)}
JavaScript
// original solution (column 1) sets quantized class values
var color = d3.scale.quantize()
.domain([0,1000])
.range(d3.range(11).map(function(d) { return "q" + d + "-11"; }));
// for column 2, a plain-old linear scale allows you to set colors to
// anchor points without using classes or hand-interpolation
var polylinear_color = d3.scale.linear()
.domain([0,1000])
.range(['rgb(255,0,0)','rgb(255,255,255)','rgb(0,255,0)'])
var col1 = 50;
var col2 = 150;
var val = 1;
var data = []
for (i=0;i<11;i++){
var d = {
'index': i,
'value': val,
'y': 100 + 20*i
};
data.push(d);
val += 100;
};
var svg = d3.select('#vis').append('svg')
g = svg.selectAll('g')
.data(data)
.enter().append('g');
g.append('rect')
.attr('x',col1)
.attr('y',function(d){return d.y;})
.attr('height',18)
.attr('width',20)
.attr('class',function(d){return color(d.value)})
g.append('text')
.attr('x',col1+50)
.attr('y',function(d){return d.y+13;})
.text(function(d){
return d.value.toFixed(1);
});
g.append('rect')
.attr('x',col2)
.attr('y',function(d){return d.y;})
.attr('height',18)
.attr('width',20)
.style('fill',function(d){
return polylinear_color(d.value);
});