这个 d3 代码如何从 v3 更新到 v4?

How would this d3 code be updated from v3 to v4?

var url = 'https://gist.githubusercontent.com/
d3byex/65a128a9a499f7f0b37d/raw/176771c2f08dbd3431009ae27bef9b2f2fb5
6e36/us-states.json';

d3.json(url, function (error, data) {
    var path = d3.geo.path();
    svg.selectAll('path')
        .data(data.features)
        .enter()
        .append('path')
        .attr('d', path);
});

我正在努力使我的代码尽可能保持最新,以便我可以开始使用 d3v4,但是许多教科书已经过时了。

上面的示例适用于 d3v3(如此处所示:http://bl.ocks.org/d3byex/378d68f27a1cc144aa8a

我知道 .geo.path() 需要更新为 .geoPath(),但我至少遗漏了另一个需要进行的更新才能使其符合d3v4.

在d3v3中d3.geo.path使用默认投影,美国Albers投影:

d3.geo.path()

Creates a new geographic path generator with the default settings: the albersUsa projection and a point radius of 4.5 pixels. (link)

在d3v4中,默认投影是空投影:

path.projection([projection]) <>

If a projection is specified, sets the current projection to the specified projection. If projection is not specified, returns the current projection, which defaults to null. (link)

这就是您的数据在 d3v3 地图中适当缩放和居中的原因,尽管如果它在其他任何地方则不会如此。

geoPath 的 d3v4 默认投影只是将数据中的坐标转换为 svg 坐标,无需转换或投影。因此,在 d3v4 中,您的数据需要投影才能正确呈现(它已绘制,但由于美国的所有 x 坐标均为负数,因此它不在屏幕上)。要使用 v3 的默认投影(美国阿尔伯斯复合投影),您可以使用:

var projection = d3.geoAlbersUsa();
var path = d3.geoPath().projection(projection);

然后照原样去做其他事情:

        var width = 950, height = 500;
        var svg = d3.select('body')
            .append('svg')
            .attr("width",width)
            .attr("height",height);

        var url = 'https://gist.githubusercontent.com/d3byex/65a128a9a499f7f0b37d/raw/176771c2f08dbd3431009ae27bef9b2f2fb56e36/us-states.json';
        d3.json(url, function (error, data) {
            
            var projection = d3.geoAlbersUsa()
            var path = d3.geoPath().projection(projection);
            
            svg.selectAll('path')
                .data(data.features)
                .enter()
                .append('path')
                .attr('d', path);
        });
    <script src="http://d3js.org/d3.v4.min.js"></script>