Reading csv data using D3.csv, each column in a separate array

I am new to working with D3.js and html / js in general, and I am trying to figure out how to read in a CSV file into separate arrays using d3.csv. I have a csv file that looks like this:

cause, prevalence, disability;
cancer, .3, .4;
aids, .5, .5;
malaria, .2, .1;

I am currently struggling with creating arrays for “cause,” “prevalence,” and “disability.” Here is the code I'm using:

<html>
  <script type="text/javascript" src="../d3/d3.js"></script>
  <script type="text/javascript" src="../d3/d3.csv.js"></script>
  <script type="text/javascript">
    d3.csv('disability.csv', function(csv){
      var cause=csv[0];
      var prevalence=csv[1];
      var disability=csv[2];
      for (i=0;i<cause.length;i++)
      {
        document.write(cause[i] + "<br />");
      }
    })
  </script>
</html>

The part document.writeis just to verify that I read the data.

+5
source share
1 answer

Looks like you mean var cause = csv[0]to indicate the first variable / column, I guess? Not seeing the csv file is hard to understand for sure.

, , - javascript, , /.

csv[0] csv. d3 csv ( ) csv, :

console.log(csv[0]);
{ cause: 'A', prevalence: .1, disability: .5 }

, /, - :

var cause = [],
    prevalence = [],
    disability = [];
csv.map(function(d) {
    cause.push(d.cause);
    prevalence.push(d.prevalence);
    disability.push(d.disability);
}

, , , . d3 , , csv data , , (, .attr('y', function(d) { return d.prevalence; })], / .

+9

All Articles