如何从 D3 v5 中的 CSV 文件加载数据 [英] How to load data from a CSV file in D3 v5
问题描述
我正在尝试从 D3 中的 CSV 文件加载数据;我有这个代码:
I'm trying to load data from a CSV file in D3; I have this code:
function update (error, data) {
if (error !== null) {
alert ("Couldn't load the dataset!");
} else {
//do something
};
function changeData () {
d3.csv ("data/dataset.csv", update);
}
如果我使用 D3 v4 它工作正常,但如果我切换到 v5 它不再工作.有人可以向我解释如何修改代码以使其适用于 D3 v5?
If I use D3 v4 it works fine, but if I switch to v5 it doesn't work anymore. Can someone explain to me how to modify the code to make it work with D3 v5?
推荐答案
d3 v5 使用获取 API 并返回一个需要以下代码的承诺.
d3 v5 uses the fetch API and returns a promise requiring the below code.
d3.csv('yourcsv.csv')
.then(function(data) {
// data is now whole data set
// draw chart in here!
})
.catch(function(error){
// handle error
})
以防将来人们想要 v4.d3 v4 另一方面,使用 XMLHttpRequest 方法,并且不返回需要此代码的承诺
In case in the future people want v4. d3 v4 on the other hand uses the XMLHttpRequest method, and does not return a promise requiring this code
d3.csv('yourcsv.csv', function(data) {
//whole data set
// draw chart here
})
csv 加载是异步的,因此请确保在 csv 函数中运行您的图表代码.
csv loading is async so make sure to run your chart code within the csv function.
这篇关于如何从 D3 v5 中的 CSV 文件加载数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!