d3 在地图上手动为州着色



学习d3js,我遵循了很多教程。现在,我能够从 json 文件为所有州创建具有相同颜色的简单美国地图。我找到了很多创建分区统计图的教程,但是我只想手动为这张地图中的一个州着色(假设阿拉巴马州,这是 json 文件中的第一个功能)。

到目前为止,这是代码:

        var w = 500;
        var h = 300;
        var svg = d3.select("body")
                    .append("svg")
                    .attr("width", w)
                    .attr("height",h);
        var projection = d3.geo.albersUsa().translate([w/2,h/2]).scale([500]);         
        var path = d3.geo.path().projection(projection);
        d3.json("us-states.json", function(json){
            svg.selectAll("path")
                .data(json.features)
                .enter()
                .append("path")
                .attr("d",path)
                .style("fill","teal");
        });

而 JSON 具有以下结构:

{"type":"FeatureCollection","features":
[{"type":"Feature","id":"01","properties":{"name":"Alabama"},"geometry":
{"type":"Polygon","coordinates":[[[-87.359296,35.00118],    [-85.606675,34.984749],[-85.431413,34.124869],[-85.184951,32.859696],...

我不知道从哪里开始。我是否需要第二个 d3.json 函数,仅将阿拉巴马州作为所选路径,或者我可以使用现有的 d3.json 函数来完成?

我认为您可以添加这样的东西:

svg.selectAll("path")
.attr("fill", function(d) {
    if(d.id === '01'){
      return #COLOUR;
    }
});

您可以通过路径的 id 为路径着色

像这样:

 g.selectAll("path")
    .data(topojson.feature(us, us.objects.states).features)
    .enter().append("path")
    .attr("d", path)
    .style("fill", function(d) {
      if (d.id == 22) {
        return "red";//on condition match
      }
    })
    .attr("class", "feature")

此处的工作代码

最新更新