gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:02:57 25 4
gpt4 key购买 nike

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 中使用默认投影,美国阿尔伯斯投影:

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 map 中适当缩放和居中,但如果它在其他任何地方则不会如此。

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>

关于javascript - 这个 d3 代码如何从 v3 更新到 v4?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46225993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com