Filling Features

Adding colors to the features of a topojson map, which has additional data injected from an external csv file as detailed in this post, is fairly straightforward. Data from Natural Earth Data and the Happy Planet Index.

Download the topoJSON file used in this example.

//general variables
var width = 800;
var height = 600;

//setup our projection
var projection = d3.geo.robinson()
    .center([0, 0])
    .scale(100)
    .translate([width/2,height/2])
    .rotate([0,0,0])

    //only for ortho projection
    //.clipAngle(90)
;

//make svg container
var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
;

//load d3 path generator
var path = d3.geo.path()
            .projection(projection)
;

//sphere for ocean and outline
svg.append("path")
  .datum({type: "Sphere"})
  .attr("class", "outline")
  .attr("d", path)
  .call(d3.behavior.drag()
    .origin(function() { 
        var currentRotation = projection.rotate(); 
        return {x: currentRotation[0], y: -currentRotation[1]}; 
     })
     .on("drag", function() {
        var rotate = projection.rotate();
        var sensitivity = .25;
        projection.rotate([d3.event.x * sensitivity, -d3.event.y * sensitivity, 0]);
        svg.selectAll("path").attr("d", path);

    })
  )    
 ;

//create svg group to hold objects
var g = svg.append("g");

//create scale for mapping the HPI values (roughly in the domain of 20 to 65) to the 8-bit 
//range allowed in rgb color values (0 to 255).
var happyScale = d3.scale.linear()
                  .domain([20,65])
                  .range([0,255])
                  ;

// load world map!
d3.json("hpi.json", function(error, topology) {
    g.selectAll("path")
      .data(topojson.object(topology, topology.objects.countries).geometries)
      .enter()

      //Make a path per country
      .append("path")
      .attr("fill" , function(d){

          //New Stuff for Filling!
          var happyColor = d.properties.happy;
          happyColor = d3.round(happyScale(happyColor));

          return "rgb(" + happyColor + ",0," + happyColor + ")" 
        })

      .attr("d", path)
      .attr("class","country")
      .call(d3.behavior.drag()
          .origin(function() { 
                var currentRotation = projection.rotate(); 
                return {
                    x: currentRotation[0], y: currentRotation[1]
                }; 
          })
          .on("drag", function() {
                var rotate = projection.rotate();
                projection.rotate([d3.event.x * sensitivity, -d3.event.y * sensitivity, 0]);
                svg.selectAll("path").attr("d", path);

          })
        );     
});