Search code examples
javascriptjquerycolorsd3.jscolorbrewer

D3.js Choropleth Map - Change Color Scheme On Selection


I have a choropleth maps of U.S. states showing total population using a quantile scale. I also have set up a drop-down menu to allow a user to select a color scheme of their choice using colorbrewer defined color schemes. On selection the map is filled with the new color scheme.

My problem is on a color scheme selection, the shapes are filled with just one color in the color scheme rather than a range of colors based on the population value. I know the issue is that I’m not actually accessing data properties.value in “path". I just don’t know what I need to do to make this happen. Any suggestions are appreciated. Here is my color change function:

$('#ColorSelection').change(function(){
    newColor = $('#ColorSelection').val();

   var colorSchemeSelect = newColor;
   var colorScheme = colorbrewer[colorSchemeSelect];

   var color = d3.scale.quantile()
     .range(colorScheme[5]);

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

 });

Solution

  • The problem is that you are replacing your old color scale, not just updating it's range, and you never set a domain on the new scale.

    var color = d3.scale.quantile() //create new quantile scale
         .range(colorScheme[5]); //set it's range
    

    If you have your scale stored in a variable color, just modify it in the event handler:

    color.range(colorScheme[5]); //change the range