Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

javascript - How to read in CSV with d3 v4?

I'm just having a little trouble understanding the documentation for CSV Parse with D3. I currently have:

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

But I keep on getting the error:

Uncaught TypeError: d3.parse is not a function

What is this supposed to look like? I'm just a little confused, and the only examples that I could find was something like this.

I also tried something like:

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

and got:

Uncaught TypeError: Cannot read property 'parse' of undefined

Why is this happening? Any help would be greatly appreaciated, thanks!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is some misunderstanding here: you're confusing d3.csv, which is a request, with d3.csvParse, which parses a string (and also mixing D3 v3 syntax with D3 v4 syntax). This is the difference:

d3.csv (D3 v4)

The d3.csv function, which takes as arguments (url[[, row], callback]):

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

So, as you can see, you use d3.csv when you want to request a given CSV file at a given url.

For example, the snippet below gets the CSV at the url between quotes, which looks like this...

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

... and logs the parsed CSV file, check it:

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...