如何从D3 v5中的CSV文件加载数据 [英] How to load data from a CSV file in D3 v5

查看:646
本文介绍了如何从D3 v5中的CSV文件加载数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从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 使用fetch 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆