我只是有点难以理解 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/