How to read in CSV with d3 v4?

前端 未结 5 1397
猫巷女王i
猫巷女王i 2020-12-15 06:02

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

d3.parse(\"data.csv\",function(data){
    salesDa         


        
5条回答
  •  难免孤独
    2020-12-15 06:36

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

    d3.csvParse

    On the other hand, d3.csvParse (or d3.csv.parse in D3 v3), which takes as arguments (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.

    So, you use d3.csvParse when you want to parse a string.

    Here is a demo, suppose you have this string:

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

    If you want to parse it, you'll use d3.csvParse, not d3.csv:

    var data = "foo,bar,baz\n42,33,42\n12,76,54\n13,42,17";
    
    var parsed = d3.csvParse(data);
    
    console.log(parsed);

提交回复
热议问题