如何使用d3js v5将CSV文件读入数组 [英] How do I read a CSV file into an array using d3js v5

查看:98
本文介绍了如何使用d3js v5将CSV文件读入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个数据仪表板,该数据仪表板应允许用户指向其文件系统上的CSV文件,然后将其上传到仪表板中以对其执行各种可视化操作.

I am creating a data dashboard that should allow the user to point to a CSV file on their file system, which is then uploaded into the dashboard to perform all kinds of visualisation actions on it.

我正在使用一个很好的d3js示例进行可视化,但是我发现的所有示例都没有读取CSV文件,因此我无法使其正常工作.我可以读取CSV文件并将其内容记录到控制台,但是无论我如何将数据传递到数组中(以后我都可以将其用作可视化的基本数据),根本无法将数组用作JS甚至是d3js变量.

I am using a nice d3js example for the visualisation, but none of the examples I found include reading the CSV file and I cannot make it work. I can read the CSV file and log the contents to the console, but whatever I do to pass the data into an array (which I can subsequently use as the basic data to visualise), there is simply no way my array becomes available as a JS or even a d3js variable.

这是我正在使用的文件的一部分-提供欧盟各个国家/地区正在使用的汽车数量.

Here is part of the file I am using - giving numbers of cars that are in use in various EU countries.

Country;Car;Van;Truck;Total
Austria;4748048;375163;78539;5201750
Belgium;5587415;678801;159623;6425839
Croatia;1489338;127395;45757;1662490

由于定界符是分号,因此我使用dsv函数,以便可以显式设置定界符.

As the delimiter is a semicolon, I am using the dsv function so that I can explicitly set the delimiter.

function getCSVdata( ) {
    var myData = [];
    d3.dsv(";","EU-cars.csv", function(d) {
        return {
            State : d.Country,
            freq: { 
                low  : d.Car,
                med  : d.Van,
                high : d.Truck
            }
        };
    }).then( function(d) {
        myData.push( d );
        console.log( d );
    }); 
    return myData;
}

将返回值分配给名为'freqData'的变量(仅使用此处的现有示例代码来尝试解决该问题-如果我在JS中声明该对象而不是从CSV文件中读取该对象,则使用的代码有效的文件).

The return value is assigned to a variable named 'freqData' (just using the existing sample code here to try and localise the problem - the used code works file if I declare the object in JS instead of reading it from a CSV file).

将'freqData'对象写入控制台,表明它是一个包含1个元素的数组.将"freqData [0]"写入控制台将显示一个数组,其中包含所有预期的26条记录.但是尝试写入"freqData [0] .length"会产生错误,因为该错误是未定义的.尝试使用警报会导致错误.

Writing the 'freqData' object to my console shows that it is an array with 1 element. Writing 'freqData[0]' to the console shows an array with all expected 26 records. But trying to write 'freqData[0].length' gives an error as that is undefined. Trying to use alert causes an error.

对于那些拥有大量d3js和其他JS经验的人来说,这可能是简单的事情,但对于新手来说却太复杂了.

This may be something simple for those who have tons of d3js and other JS experience but it turns out to be too complex for newbies.

我需要使用最新的(v5)d3js,它使用的Promise对象对我来说是全新的.我无法通过阅读各种所谓的已知方法中的大量局部信息来弄清楚.如果有人可以发表一个完整的工作示例,即读取CSV并将数据传递给JS对象,那将是很棒的.我的精力和时间都快用完了.

I need to use the latest (v5) of d3js, which is using the Promise object that is totally new to me. I cannot figure it out by reading tons of partial info on all kinds of supposedly known methods. If someone can just post a fully working example of reading a CSV and passing the data to a JS object that would be wonderful. I am running out of steam and time.

谢谢

4everJang

4everJang

推荐答案

运行代码时,您应该看到确实在加载数据.当我在dsv/csv文件中使用示例数据并运行您的函数时,将以下内容记录到控制台:

When you run your code you should see that you are indeed loading the data. When I use your example data in a dsv/csv file and run your function I get the following logged to console:

基于then方法中的控制台日志,它显示为dsv文件的加载成功和行功能都成功.

So it appears as both your load of the dsv file is successful, and your row function is successful, based on the console log in the then method.

让我们仔细研究一下.then方法,该方法在文件加载并应用行功能之后运行,或者在完成诺言之后运行.因此,这里的关键部分是then方法直到兑现了诺言之后才执行提供的功能.在我们等待实现承诺的过程中,代码将继续执行,在您的情况下,return语句将执行-在数据完全加载之前,因此在then方法执行之前.这意味着您没有返回任何数据,这就是您的问题.

Let's take a closer look at the .then method, this runs after the file has loaded and the row function been applied - or, once the promise has been fulfilled. So the key part here is the then method doesn't execute the provided function until after the promise is fulfilled. While we are waiting for the the promise to be fulfilled, code continues to be executed, in your case the return statement executes - before the data is fully loaded and therefore before the then method executes. This means you aren't returning any data, and this is your problem.

使用行函数获取数据的最简单且可能是最常见的d3模式是将需要加载的数据的代码放置在.then方法的实现函数中:

The simplest and probably most common d3 patterns to fetch the data with your row function is to either place code that requires the loaded data in the .then method's fulfillment function:

function getCSVdata( ) {
    d3.dsv(";","https://raw.githubusercontent.com/Andrew-Reid/SO/master/dsv.csv", function(d) {
        return {
            State : d.Country,
            freq: { 
                low  : d.Car,
                med  : d.Van,
                high : d.Truck
            }
        };
    }).then(function(data) {
      console.log("file has " + data.length + " rows");
      logger(data);
    }); 
}

getCSVdata();

function logger(data) {
	console.log(data);
}

.as-console-wrapper { max-height: 100% !important; top: 0; }

<script src="https://d3js.org/d3.v5.min.js"></script>

或者您可以采用略有不同的形式:

Or you could take a slightly different form:

function getCSVdata( ) {
    d3.dsv(";","https://raw.githubusercontent.com/Andrew-Reid/SO/master/dsv.csv", function(d) {
        return {
            State : d.Country,
            freq: { 
                low  : d.Car,
                med  : d.Van,
                high : d.Truck
            }
        };
    }).then(fulfilled); 
}

getCSVdata();

function fulfilled(data) {
	// do stuff here:
    console.log(data);
}

.as-console-wrapper { max-height: 100% !important; top: 0; }

<script src="https://d3js.org/d3.v5.min.js"></script>

这篇关于如何使用d3js v5将CSV文件读入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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