Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3 seems to assume I know the column names of a csv?

I have csv files that are generated, and I am trying to load them into d3 to graph them. The column names are based on the data, so I essentially can't know them in advance. With testing, I am able to load this data and graph it all well and nice if I know the names of the columns...but I don't in my use case.

How can I handle this in d3? I can't seem to find anything to help/reference this online or in the documentation. I can see when I log to the console data[0] from d3.csv that there are two columns and the values read for them, but I don't know how to refer arbitrarily to column 1 or 2 of the data without knowing the name of the column ahead of time. I'd like to avoid that in general, knowing my timestamps are in column 1 and my data is in column 2, if that makes sense.

Edit, my answer uses d3.entries to help learn the name of the unknown column, and then continues to access all objects with that index:

d3.csv("export.csv", function(error, data) {
    var mappedArray = d3.entries(data[0]);
    var valueKey = mappedArray[1].key;
    data.forEach(function(d) {
        ...
        d.value = d[valueKey];
    }
}
like image 721
cdietschrun Avatar asked Feb 27 '13 20:02

cdietschrun


2 Answers

You can use the d3.entries() function to transform an associative array into another array that contains an associative array with key and value keys for each key-value pair.

like image 186
Lars Kotthoff Avatar answered Sep 23 '22 15:09

Lars Kotthoff


I'm glad you figured it out, @cdietschrun.

Version 4 of D3 allows you to do this a little more simply. It introduces a columns property, which creates an array of column headers (i.e. the dataset's 'keys').

So, instead of using your code:

var mappedArray = d3.entries(data[0]),
    valueKey = mappedArray[1].key;

... you can use:

var valueKey = data.columns;
like image 45
Markus Avatar answered Sep 25 '22 15:09

Markus