Stophface Stophface - 3 months ago 14
Javascript Question

Return thresholds from quantized colorscale d3

I am using

d3.scale.quantize()
and the
colorBrewer
to get a colorscale.

....
var extent = d3.extent(collection.features, function(d) {
return d.properties.mean;
});

var colorScale = d3.scale.quantize()
.domain(extent)
.range(colorbrewer.RdYlBu[8]);
...


That gives me
8
different colors, corresponding to certain ranges of given values.
I then use
coloScale
to fill the
svg


....
.attr("fill-opacity", 0.1)
.attr("stroke", "grey")
.style("fill", function(d) {
return colorScale(d.properties.mean);
});
...


How do I know which range of values corresponds to the color
"#fdae61"
or
"#fee090"
? How would I access these values?
I need them to make a legend...

Answer

What you need is quantize.invertExtent(value):

Returns the extent of values in the domain [x0, x1] for the corresponding value in the range: the inverse of quantize. This method is useful for interaction, say to determine the value in the domain that corresponds to the pixel location under the mouse.

So, suppose that we have a domain going from 0 to 100:

var colorScale = d3.scale.quantize()
    .domain([0, 100])
    .range(["#d73027", "#f46d43", "#fdae61", "#fee090", "#e0f3f8", "#abd9e9", "#74add1", "#4575b4"]);

This gets the domain extent to the color #fdae61, for instance:

console.log(colorScale.invertExtent("#fdae61"));//returns [25, 37.5]

Check the snippet:

var colorScale = d3.scale.quantize()
    .domain([0, 100])
    .range(["#d73027", "#f46d43", "#fdae61", "#fee090", "#e0f3f8", "#abd9e9", "#74add1", "#4575b4"]);
		
		
console.log(colorScale.invertExtent("#fdae61"));
console.log(colorScale.invertExtent("#fee090"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Comments