1

First I read the csv file and fill an empty array with data

        //Load dataset
        var dataset = [];
        var subset = [];

        d3.csv("datafile.csv", function(d){
            for (var i = 0; i < d.length; i++){
                if (d[i].year == 2013)
                    {
                        subset.push(d[i].name);
                        subset.push(d[i].year);
                        subset.push(d[i].value1);
                        subset.push(d[i].value2);
                        subset.push(d[i].value3);
                        dataset.push(subset.concat());
                        subset = [];
                    }
                else
                    {
                    }
            }
        });

Then set up the xScale

            var w = 700; //width of SVG
            var xmax = 0.02 //margin of xAxis
            var xScale = d3.scale.linear()
                    .domain([d3.max(dataset, function(d){ return +d[2]; }) + xmax , 0])
                    .range([0, w]);

I checked in console, dataset is filled, but xScale(Number) returns NaN however, if I copy the xScale section code and execute in console xScale(Number) will work.

user2901633
  • 989
  • 1
  • 8
  • 15
  • Without seeing all the code it's difficult to say, but are you trying to specify the domain before you populate the subset variable. You can set up the domain inside the csv callback, after subset has been filled. So you would put the xScale.domain line inside the csv callback. – user1614080 Mar 31 '14 at 06:34
  • Hey finally got it to work, you were right. I put everything inside the csv callback and Voilà. But one thing I still dont get is that the variable dataset should be a global variable and I should be able to call it outside the function?..anyway I guess I will read more about the basic about javascript. – user2901633 Apr 01 '14 at 03:35
  • You can post it as an answer for other's if you want. For your information the d3.csv call is asynchronous, so the code outside of the callback will continue to run while javascript is waiting for the file to load. I imagine that your original call to the scale object happened before the file was loaded, hence the code not working. You can use [queue](https://github.com/mbostock/queue) to get around this. Also, you might find this [question and answer](http://stackoverflow.com/questions/9491885/csv-to-array-in-d3-js) helpful to understand how it all works. – user1614080 Apr 01 '14 at 08:09

0 Answers0