How to load data from a CSV file in D3 v5

主宰稳场 提交于 2019-12-24 18:42:44

问题


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);
}

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?


回答1:


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   
  })

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 loading is async so make sure to run your chart code within the csv function.




回答2:


@pmkro's answer is good, but if you want to use ES7 async/await instead of Promise.then:

async function doThings() {
  const data = await d3.csv('yourcsv.csv');
  // do whatever with data here
}

doThings();


来源:https://stackoverflow.com/questions/58093568/text-and-arc-not-visible-d3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!