根据键设置等值线的颜色

Set the color in a choropleth based on the key

我正在尝试根据链接到键的一些属性来设置等值线的颜色。 然而,所有设置颜色的方法都只有那个特定地方的值,而没有它的键。

var map = dc.geoChoroplethChart(dom)
  .height(width*0.8)
  .width(width)
  .dimension(dim)
  .projection(projection)
  .colorAccessor(function(d,i){
    // it isn't the usual d={key,value} but only d=value
  })
  .colorCalculator(function(d,i){
    // it isn't the usual d={key,value} but only d=value
    //and it's deprecated
  })
  .title(function (d) {return d.key + ': ' + d.value;})
  // got the key,value as expected

如何从 colorAccessor 获取密钥?它在其他功能(例如标题)中工作正常

原来是 "normal"。正如 Gordon 所建议的那样,解决方案是将 geojson 的索引映射到您想要的数据。就我而言,我在国家数组中有关于每个国家的额外数据:

  var geojson=topojson.feature(europe,europe.objects.countries);
  // map index in the map to country data this hack is to solve a problem of not having the key on the colorAccessor
  var geo2data=[];
  geojson.features.forEach(function(d,i1){
    var i2=country.findIndex(function(c) {
      return c.country.toUpperCase()==d.id});
    geo2data[i1] = i2;
  });

  var map = dc.geoChoroplethChart(dom)
  ...
  .colorAccessor(function(v,i){
    if (geo2data[i] >= 0){
      //geo2data[i] contains extra values, eg 
      return v / country[geo2data[i]].threshold;
    }
    return v;
  })

我最终使用的解决方法: 创建一个自定义 reduce 函数,复制值中的键。

  //the iso code of the country is the key
  var group = dim.group().reduce(
    function (p, v) {
      p.total += +v.total;
      if (p.iso == "") {
        p.iso = v.country;
      }
      return p;
    },
    function (p, v) {
      p.total -= +v.total;
      return p;
    },
    function () { return {
       total:0,iso:""
      };
    });

 var map = dc.geoChoroplethChart(dom)
  .colorAccessor(function(d){
    if (!d || !d.value.iso) 
      return null; // area without data
    // now d.value.iso contains the key, and d.value.total contains the value
    return colorIndex(d.value.iso,d.value.total);// do magic
  })
  ....