javascript - 如何使用 d3 v4 读取 CSV?

标签 javascript csv d3.js

我只是有点难以理解 CSV Parse 的文档与 D3。我目前有:

d3.parse("data.csv",function(data){
    salesData = data; 
});

但是我一直报错:

Uncaught TypeError: d3.parse is not a function

这应该是什么样子?我只是有点困惑,我能找到的唯一例子是 this。 .

我也试过类似的东西:

d3.dsv.parse("data.csv",function(data){
    salesData = data; 
});

得到:

Uncaught TypeError: Cannot read property 'parse' of undefined

为什么会这样?任何帮助将不胜感激,谢谢!!

最佳答案

这里有一些误解:你混淆了d3.csv,它是一个请求,d3.csvParse,它解析一个字符串(并且混合了 D3 v3 语法与 D3 v4 语法)。这是区别:

d3.csv (D3 v4)

d3.csv函数,它以 (url[[, row], callback]) 为参数:

Returns a new request for the CSV file at the specified url with the default mime type text/csv. (emphasis mine)

因此,如您所见,当您想要在给定的 url 请求给定的 CSV 文件时,您可以使用 d3.csv

例如,下面的代码片段在引号之间的 url 中获取 CSV,看起来像这样......

name, parent
Level 2: A, Top Level
Top Level, null
Son of A, Level 2: A
Daughter of A, Level 2: A
Level 2: B, Top Level

... 并记录已解析的 CSV 文件,检查它:

d3.csv("https://gist.githubusercontent.com/d3noob/fa0f16e271cb191ae85f/raw/bf896176236341f56a55b36c8fc40e32c73051ad/treedata.csv", function(data){
    console.log(data);
});
<script src="https://d3js.org/d3.v4.min.js"></script>

d3.csv解析

另一方面,d3.csvParse (或 D3 v3 中的 d3.csv.parse),它以 (string[, row]) 为参数:

Parses the specified string, which must be in the delimiter-separated values format with the appropriate delimiter, returning an array of objects representing the parsed rows.

因此,当您想要解析字符串时,您可以使用 d3.csvParse

这是一个演示,假设你有这个字符串:

var data = "foo,bar,baz\n42,33,42\n12,76,54\n13,42,17";

如果你想解析它,你将使用d3.csvParse,而不是d3.csv:

var data = "foo,bar,baz\n42,33,42\n12,76,54\n13,42,17";

var parsed = d3.csvParse(data);

console.log(parsed);
<script src="https://d3js.org/d3.v4.min.js"></script>

关于javascript - 如何使用 d3 v4 读取 CSV?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42285441/

相关文章:

python - 当我传递 skip_footer arg 时,Pandas read_csv 忽略列数据类型

javascript - 将 D3 图表嵌入到 Handlebars 模板中

javascript - 使用php将多个列表框元素存储到数据库中

javascript - 在对数组执行 "double iteration"的同时对每个项目执行异步操作

python - python sqlalchemy可以使用变量构造插入语句(针对mysql数据库)

charts - 人力车-js图表库: Need strings instead of numbers on axes

javascript - 如何修复带有文本的气泡图中的可拖动功能?

javascript - ng-repeat 中的数组未显示

php - 如何使用javascript模拟点击href为php的链接

mysql - 加载数据文件(来自 csv): data too long for column 'xxx' at row N