D3: scale and color for choropleth map

2.8k views Asked by At

I'm working on a D3 map as one of several prototypes for a project involving small areas statistics. I'm starting with a simple map and I am new to D3.

I have not been able to display a range of colors using either a threshold or quantile scale. I have written at least 6 examples to experiment with the many other examples that already exist but I simply cant get the range to display in the areas. I know I am close but there is something I am missing.

My example is on git at https://github.com/Monduiz/OL-explorer. I really would appreciate any insights to help me understand what I'm doing wrong.

Here's the code I'm working with and the files are available at the link above.

var width = 960,
    height = 500;

var colors = d3.scale.quantize()
    .domain([0, 1])
    .range(colorbrewer.YlOrRd[7]);

var projection = d3.geo.azimuthalEqualArea()
    .rotate([100, -45])
    .center([5, 20])
    .scale(800)
    .translate([width/2, height/2])

var path = d3.geo.path()
    .projection(projection);

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

queue()
    .defer(d3.json, "OLMCSDfr.json")
    .defer(d3.csv, "data.csv")
    .await(ready);

function ready(error, can, OLM) {
  var PopById = {};

OLM.forEach(function(d) { PopById[d.Id] = +d.OLMnb; });

  svg.append("g")
    .attr("class", "SDR")
    .selectAll("path")
    .data(topojson.feature(can, can.objects.OLMCSDfr).features)
    .enter().append("path")
    .attr("d", path)
    .style("fill", function(d) { return colors(PopById[d.Id]); });
  }

1

There are 1 answers

3
Ben Southgate On BEST ANSWER

In your ready function, you are referencing d.Id for each of the topojson features, which is currently undefined.

I switched your function passed to fill to grab d.properties.SDRID instead, which is in both the topojson features and your OLM list elements. The forEach statement must also be changed to match.

This seems to work:

function ready(error, can, OLM) {
  var PopById = {};

  OLM.forEach(function(d) { PopById[d.SDRID] = +d.OLMnb; });

  svg.append("g")
      .attr("class", "SDR")
    .selectAll("path")
      .data(topojson.feature(can, can.objects.OLMCSDfr).features)
    .enter().append("path")
      .attr("d", path)
      .style("fill", function(d) { 
        return colors(PopById[d.properties.SDRID]); });

}