1

I'm having issues understanding d3. I'm trying to load a bunch of .csv files while have a timestamp in the left column and an integer in the right column, representing the number of people present at any point in time in a classroom (every classroom has its own .csv).

Now the idea is to make a pie chart representing a day's worth of people present divided between the multiple classrooms. For example, 65 % classroom 1, 23 % classroom 2 and 12 % classroom 3.

I'm struggling to understand how i would even go about reading these, apparently everything inside the d3.csv() parser is outside the scope of everything outside of it, which is very counter intuitive. I cannot access the things I'm parsing from outside the .csv() method, which is weird, because I'm reading the .csv files as following:

var files = ["Bibliotheek S2.csv","Bibliotheek S8.csv","Euclides S23.csv","Lovelace Ledeganck.csv","Mercator S8.csv","Nadar S8.csv","Ortelius S8.csv","Practicum S2.csv","S12.csv","Thetis INW.csv","Turing S9.csv","Van Straelen S8.csv","Zuse S9.csv"];

dt = {};
files.forEach(function(f){
    d3.csv("lokalen/"+f,function(data){
        dt[f] = data;
    });
});

How would i continue with this? I'm absolutely lost here.

Thanks, Milan

Rmo
  • 61
  • 7
  • You could nest the calls...check this [answer](http://stackoverflow.com/questions/21842384/importing-data-from-multiple-csv-files-in-d3). – FernOfTheAndes May 16 '14 at 00:57

1 Answers1

0

It's not quite that everything within the scope of d3.csv() is unavailable: d3.csv() is asynchronous. In a nutshell, code in the d3.csv() callback isn't executed until after the csv file downloads. But, code after d3.csv() executes immediately. In your case, if you try to access dt immediately after your files.forEach loop, the files will not have downloaded yet.

To get around that, you need to figure a way to make the rest of your application wait until all the files are downloaded. For example:

var files = ["Bibliotheek S2.csv","Bibliotheek S8.csv","Euclides S23.csv","Lovelace Ledeganck.csv","Mercator S8.csv","Nadar S8.csv","Ortelius S8.csv","Practicum S2.csv","S12.csv","Thetis INW.csv","Turing S9.csv","Van Straelen S8.csv","Zuse S9.csv"];

files.forEach(function(f){
    d3.csv("lokalen/"+f,function(data){
      dt[f] = data;
      if (d3.keys(dt).length == files.length){
      // Whatever you'd like to do once you load all the data
      console.log(d3.keys(dt)) // For example to check our work 
      }
    });
});

When each file finishes loading, that if statement checks to see if all files have been stored in dt. If so, it works with all of the data; if not, no action is taken until the next file loads, when it checks again. The final file will execute whatever you'd like to do with the full dataset.

Sean Easter
  • 859
  • 8
  • 16