Search code examples
javascriptd3.jscolor-scheme

Using a diverging colour scheme


When I try to apply a diverging colour scheme in d3, e.g. d3.interpolateSpectral with sequential scale, it always returns:

Uncaught TypeError: t is not a function

As there is no "t" in the code I write, I suppose it is related to the "t" in the original colour scheme If yes, I am not sure how that is applied, as I refer an example for the use of that colour scheme there is no address of the "t" neither

Here is the related code for the colour Scale:

var color=d3.scaleSequential(d3.interpolateSpectral);

color.domain([d3.min(data, function(d){return d.population;}), 
                            d3.max(data, function(d){return d.population;})]);

selection.style("fill", function(d){                    
    var value=d.properties.value;                   
    if(value){
        return color(value);
    } else{
        return "#ccc";
    }

Any help will be appreciated, thanks!


Solution

  • Given your error, you're probably using D3 v4. If that's correct, you have to reference the scale-chromatic mini-library:

    <script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
    

    Have a look at this demo, without referencing the mini-library we get the same error (open your browser's console to see it):

    var color = d3.scaleSequential(d3.interpolateSpectral);
    
    console.log(color(1))
    <script src="https://d3js.org/d3.v4.min.js"></script>

    We don't see the error anymore if we reference the mini-library:

    var color = d3.scaleSequential(d3.interpolateSpectral);
    
    console.log(color(1))
    <script src="https://d3js.org/d3.v4.min.js"></script>
    <script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>

    Finally, it's worth mentioning that, using D3 v5, we don't have to reference it:

    var color = d3.scaleSequential(d3.interpolateSpectral);
    
    console.log(color(1))
    <script src="https://d3js.org/d3.v5.min.js"></script>