d3.js v5 数据加载
d3提供了几种数据加载的方式:
- d3.csv()
- d3.json()
- d3.tsv()
- d3.xml()
d3.js 数据加载在 v5 版本之后有重大的变化:
D3现在使用Promises而不是异步回调来加载数据。Promises简化了异步代码的结构,尤其是在支持async和await的现代浏览器中。
Changes in D3 5.0
Released March 22, 2018.
D3 5.0 introduces only a few non-backwards-compatible changes.
D3 now uses Promises instead of asynchronous callbacks to load data. Promises simplify the structure of asynchronous code, especially in modern browsers that support async and await. (See this introduction to promises on Observable.) For example, to load a CSV file in v4, you might say:
d3.csv("file.csv", function(error, data) {
if (error) throw error;
console.log(data);
});
In v5, using promises:
d3.csv("file.csv").then(function(data) {
console.log(data);
});
Note that you don’t need to rethrow the error—the promise will reject automatically, and you can promise.catch if desired. Using await, the code is even simpler:
const data = await d3.csv("file.csv");
console.log(data);
With the adoption of promises, D3 now uses the Fetch API instead of XMLHttpRequest: the d3-request module has been replaced by d3-fetch. Fetch supports many powerful new features, such as streaming responses. D3 5.0 also deprecates and removes the d3-queue module. Use Promise.all to run a batch of asynchronous tasks in parallel, or a helper library such as p-queue to control concurrency.
D3 no longer provides the d3.schemeCategory20* categorical color schemes. These twenty-color schemes were flawed because their grouped design could falsely imply relationships in the data: a shared hue can imply that the encoded data are part of a group (a super-category), while relative lightness can imply order. Instead, D3 now includes d3-scale-chromatic, which implements excellent schemes from ColorBrewer, including categorical, diverging, sequential single-hue and sequential multi-hue schemes. These schemes are available in both discrete and continuous variants.
D3 now provides implementations of marching squares and density estimation via d3-contour! There are two new d3-selection methods: selection.clone for inserting clones of the selected nodes, and d3.create for creating detached elements. Geographic projections now support projection.angle, which has enabled several fantastic new polyhedral projections by Philippe Rivière.
Lastly, D3’s package.json no longer pins exact versions of the dependent D3 modules. This fixes an issue with duplicate installs of D3 modules.
我发现我在使用d3.js v6 版本加载中国地图的json文件渲染地图的时候,湖北省的path出现了错误,当我降低版本到v5之后错误得到的解决。