0

I'm learning d3.js and I'm having a problem pushing a simple data from a csv file. The error at the console is: "ReferenceError: Can't find variable: data"

Apparently, the compiler can't identify the method .data() from d3. The one we call to iterate the svg elements:

const circles = svg.selectAll("circles").data(data);

Before this statement, I called the data like this and it is showing normally on the console.

    d3.csv("data/HousePricesAroundtheWorld.csv").then((data) => {
  data.forEach((d) => {
    d.number = Number(d["annual percent change"]);
  });
  console.log(data);
});

Link to the repo

Mi Azevedo
  • 39
  • 5

1 Answers1

0

In your code, data is only accessible inside of the function that you are passing to .then(). One option is to create a function that draws your chart. This function can have one parameter for the chart's data. You can pass this function to .then() so that it gets passed the data read from the file. Here's an example.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <script src="https://d3js.org/d3.v7.js"></script>
</head>

<body>
    <div id="chart"></div>

    <script>
        d3.csv('https://raw.githubusercontent.com/curran/data/gh-pages/uci_ml/iris/iris.csv', d => ({
          ...d,
          description: `${d.class}: ${d.petal_length} x ${d.petal_width}`
        }))
          .then(chart);

        function chart(data) {
           d3.select('#chart')
             .selectAll('p')
             .data(data)
             .join('p')
               .text(d => d.description);
        }
    </script>
</body>
</html>
Dan
  • 1,501
  • 9
  • 8