简体   繁体   中英

D3 CSV Import With “%”

I am attempting to import a CSV that looks like this:

Month,Ratio

January,0.19%

February,0.19%

March,0.19%

April,0.18%

The code I am using right now is:

    d3.csv("month_ct.csv", function(d) {
    return {
        month: d.Month,
        ratio: +d.Ratio // convert "Length" column to number
    }; }, 
    function(error, rows) {
    console.log(rows);
    });

My first question is how to actually access this data. I see it displayed on the console when I first open it and I am able to view its contents, but if I set the code equal to a variable, say "dataset," I'm unable to access the elements of the list.

Second, viewing the returned item has the ratios as NaN, where they should be numbers.

Finally, my code draws images that scale according to the max value in the dataset. What would be an appropriate way to iterate over the dataset to get the largest ratio? For a list of lists, I would do something like this:

    var max = 0;
    for (group in dataset) {
    if (group[1] > max) {
    max = group[1];
    }
    }

The NaN is because there's a trailing '%' on the Ratio field. You can remove it like:

ratio: +d.Ratio.slice(0, -1)

assuming that all of the Ratio fields have a trailing '%' character.

In order to iterate through the rows you'd do something like:

var max = -1;

for (var i = 0; i < rows.length; i++ ) {
    if (rows[i].Ratio > max) {
        max = rows[i].Ratio;
    }
}

EDIT: changed the name of the variable to rows to reflect a name that should be defined in the callback function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM