javascriptd3.jsdatamaps

Datamap - Change color depending on value


I came across a datamap example here and trying to edit it. I need to change the state color depending on the value, ranging from dark blue to light blue.

At the moment,

fills: {
            'lightBlue': '#cc4731',
            'justBlue': '#306596',
            'deepBlue': '#667faf',
            'mediumBlue': '#a9c0de',
            'deepBlue': '#ca5e5b',              
            'defaultFill': '#eddc4e'
        }

And the data has,

data: {
            AZ: {
                    fillKey: 'lightBlue',
                    userVisits: 5
                },
            CO: {
                    fillKey: 'justBlue',
                    userVisits: 5
                },
            DE: {
                    fillKey: 'deepBlue',
                    userVisits: 32
                },
            ....
}

But is there to generate shades of blue depending on the userVisits?


Solution

  • I don't think there is a an option to put logic in the fillkey selection. I'd recommend processing the data to assign a fillkey before giving it to Datamaps. I made a codepen to demonstrate. Also, the "fills" data has duplicate keys and hex values that do not match the color described.

    var stateData = {
            AZ: {
                    userVisits: 5
                },
            CO: {
                    userVisits: 15
                },
            DE: {
                    userVisits: 32
                }
        }
    
    function addFillKey(mapData){
      for (var mapDatum in mapData){
            var userVisits = mapData[mapDatum].userVisits;
            if(userVisits < 10){
                mapData[mapDatum].fillKey = "lightBlue"
            }else if(userVisits < 20){
                mapData[mapDatum].fillKey = "justBlue"
            }else{
                mapData[mapDatum].fillKey = "mediumBlue"
            }
        }
    }
    
    addFillKey(stateData);
    
    var map = new Datamap({
      element: document.getElementById('container'),
      scope: 'usa',
      fills: {
        'lightBlue': '#cc4731',
        'justBlue': '#306596',
        'deepBlue': '#667faf',
        'mediumBlue': '#a9c0de',
        'deepBlue': '#ca5e5b',              
        'defaultFill': '#eddc4e'
      },
      data: stateData
    
    });