d3js choropleth 不会填满

d3js choropleth won't fill

我可以用 d3js 绘制中国地图,但等值线无法填满。代码:

<script>
var margin = {top: 0, right: 0, bottom: 0, left: 0},
    width = parseInt(d3.select('#map').style('width')),
    height = width*0.7;

var places = <?php echo json_encode($provinces); ?> 

var minimum = d3.min(places, function(d) { return d.rate; }),
    maximum = d3.max(places, function(d) { return d.rate; });

var minimumColor = "#BFD3E6", 
    maximumColor = "#88419D";

var color = d3.scale
    .linear()
    .domain([minimum, maximum])
    .range([minimumColor, maximumColor]);

var projection = d3.geo.mercator()
    .center([109, 31])
    .scale(width*0.85)
    .translate([width/1.8, height/1.5])

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

var svg = d3.select("#map")
    .append("svg")
    .attr("width", width)
    .attr("height", height)
    .append("g")
    .attr("transform", "translate(0,0)");

d3.json("data/china_simplify.json", function(error, root) {

    if (error) 
    return console.error(error);
    console.log(root.features);

    var rateById = {};
    places.forEach(function(d) { rateById[d.id] = +d.rate; });

    console.log(rateById);

    svg.append("g")
        .attr("class", "provinces")
    svg.selectAll("path")
        .data( root.features )
        .enter()
        .append("path")
        .attr("d", path )
        .style("fill", function(d) { return color(rateById[d.id]); });

});
</script>

如您所见,我已经包含了 console.log(rateById);,其中 returns:

Object {1: 5829, 2: 2181, 3: 33904, 4: 14182, 5: 23290, 6: 135365, 7: 56757, 8: 21148, 9: 463618, 10: 1895, 11: 8408, 12: 12318, 13: 2990, 14: 25601, 15: 12720, 16: 41816, 17: 27993, 18: 47288, 19: 15422, 20: 24968, 21: 34515, 22: 36199, 23: 44708, 24: 20886, 25: 16609, 26: 70220, 27: 117876, 28: 84413, 29: 14271, 30: 23102, 31: 19010, 32: 16097, 33: 3783, 34: 7616}

key指的是省份的ID。这是 china_simplify.json 文件的片段:

{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"id":1,"name":"甘肃"},"geometry":{"type":"Polygon","coordinates":[[[104.35851932200904,37.40123159456249],[104.46450768428224,37.440247301072134],[104.68950687084538,37.41192861571304],[104.76474775590418,37.25049144112714],[104.92241255059872,37.096754055055584],[105.18017459508144,36.97213633912071], [...]

不确定为什么它没有正确填充!如果我删除 return color(rateById[d.id]); 并用 red 替换,那么所有内容都会填充为红色。这表明问题与 color 函数有关。

编辑

当我运行console.log( color(rateById[1]) );它returns#bfd2e5。这表明 color 函数本身没有任何问题,但由于某种原因,十六进制代码未填充到映射中。

这里可能有问题:.style("fill", function(d) { return color(rateById[d.id]); })。我似乎无法弄清楚,因为它匹配 this example.

编辑 2

我整理了一个 jsfiddle:https://jsfiddle.net/o06edvuf/

在 rateById 中,费率是通过 id 聚合的,但域的设置考虑了最小和最大费率。使用 rateById 设置颜色域:

var minimum = d3.min(d3.values(rateById)),
maximum = d3.max(d3.values(rateById));

好的,找到了

.style("fill", function(d) { 
        return color(rateById[d.properties.id]); })