0

My question:

I try to append a lot of rects in svg. But no matter how many time I tried, the Chrome browser kept show me the warn message.

Uncaught TypeError: svg.selectAll(...).data(...).enter is not a function
    at (index):39
(anonymous) @ (index):39

It said the problem is this: enter() Cannot figure out why.

My code as below

editor screen shot the whole script is

<script type="text/javascript">
      //d3.js code
      //import csv data
      var dataset; //宣告為全域變數

      d3.csv("eslite.csv", function(data) {
        dataset = data;

        //以下放入呼叫其他產生視覺圖表的函式

      });

      //設定 svg 大小
      var w = 1000;
      var h = 500;

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

      var book = svg.selectAll("rect")
                    .data(dataset)
                    .enter()
                    .append("rect")
                    .attr("width", 20)
                    .attr("height", 20)
                    .attr("rx", 3)
                    .attr("ry", 3);

    </script>
  • 3
    I guess your dataset variable is still `undefined` when your using it (because d3.csv is asynchronous so your callback function is executed once the file finished loading, most likely after the statement `svg.selectAll("rect") .data(dataset) .enter()` is exectued) – mgc Dec 25 '19 at 19:48

1 Answers1

0

Welcome to Stack Overflow.

As @mgc points out, your data isn't loaded until your callback fires.

One solution is to move your drawing code inside your callback function, like this:

<script type="text/javascript">
      //d3.js code
      //import csv data
      var dataset; //宣告為全域變數

      d3.csv("eslite.csv", function(data) {
        dataset = data;

        //以下放入呼叫其他產生視覺圖表的函式

        //設定 svg 大小
        var w = 1000;
        var h = 500;

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

        var book = svg.selectAll("rect")
                    .data(dataset)
                    .enter()
                    .append("rect")
                    .attr("width", 20)
                    .attr("height", 20)
                    .attr("rx", 3)
                    .attr("ry", 3);

      });


    </script>
Mikkel
  • 7,693
  • 3
  • 17
  • 31