Art_Knopfler
Art_Knopfler

Reputation: 93

Error with D3 data.map function

I'm trying to load a csv file with x and y coordinates and create circles with that coordinates. I've understood how to load a csv file and i can log coordinates in the console but I don't understand why the log function return Not_a_number when i try to create circles. Is there a problem with mine data.map function? Thanks

Here the code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script type="text/javascript" src="d3/d3.v3.js"></script>
<style type="text/css">
    /* No style rules here yet */       
</style>
</head>
<body>
<script type="text/javascript">

    //Width and height
    var w = 900;
    var h = 500;
    var padding = 20;
    var dataset = [];

    d3.csv("dataset.csv", function(data) {
      dataset = data.map(function(d,i) { 
        //THIS WORKS
        console.log(d);
        console.log(i);
        return [ +d["x-coordinate"], +d["y-coordinate"] 
        ]; });


    //Create SVG element
    var svg = d3.select("body")
                .append("svg")
                .attr("width", w)
                .attr("height", h);

    svg.selectAll("circle")
       .data(dataset)
       .enter()
       .append("circle")
       .attr("cx", function(d) {
            //THIS DOESNT WORK
            console.log(d);
            return d[0];
       })
       .attr("cy", function(d) {
            return d[1];
       })
       .attr("r", function(d) {
            return d[1];
       })

    });

</script>
</body>
</html>

Upvotes: 0

Views: 1970

Answers (1)

paradite
paradite

Reputation: 6436

You can only access the dataset after it has been asynchronously loaded inside d3.csv.

The code inside d3.csv is executed asynchronously, meaning it would run only after the file has been loaded, it is not guaranteed to run before the code below it.

d3.csv("dataset.csv", function(data) {
  dataset = data.map(function(d,i) { 
    //THIS WORKS
    console.log(d);
    console.log(i);
    return [ +d["x-coordinate"], +d["y-coordinate"] 
    ]; });

  //Create SVG element
  var svg = d3.select("body")
              .append("svg")
              .attr("width", w)
              .attr("height", h);

  svg.selectAll("circle")
     .data(dataset)
     .enter()
     .append("circle")
     .attr("cx", function(d) {
          //THIS DOESNT WORK
          console.log(d);
          return d[0];
     })
     .attr("cy", function(d) {
          return d[1];
     })
     .attr("r", function(d) {
          return d[1];
     })
     .text("hello world");

});

Alternatively, create a method and pass dataset into that method inside d3.csv.

Upvotes: 1

Related Questions