d3 json - 在地图中手动为州着色

d3 json - Color a state manually in a map

学习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")

工作代码here