d3js choropleth不会填

时间:2016-07-29 10:09:57

标签: d3.js choropleth

我可以用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);,它返回:

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}

密钥是指省的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]) );时,它会返回#bfd2e5。这表明color函数本身没有任何问题,但由于某种原因,十六进制代码未在地图中填充。

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

编辑2

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

2 个答案:

答案 0 :(得分:2)

好的,我找到了。

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

答案 1 :(得分:1)

在rateById中,费率是通过ID聚合的,但域是根据最小和最大费率设置的。使用rateById设置颜色域:

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