d3.js simple area chart example … getting “undefin

2020-04-21 01:53发布

问题:

I'm studying d3.js by working through the examples on d3.js.org

I'm starting with "area chart" at http://bl.ocks.org/3883195

I tried typing it in myself so I'll understand the variables and functions.

The script calls on data.tsv to make the chart.

Well, when loading data.tsv, I got an "'undefined' is not an object" error.

So I fiddled some, then just went ahead & copied and pasted bl.ock's original code into my editor, changing his d3.v3.js into d3.v2.js

Same error.

I feel that I have data.tsv in the correct directory on my machine, same directory as d3.v2.js.

Error thrown by the second line here:

    d3.tsv("data.tsv", function(error, data) { 
      data.forEach(function(d) { 
         d.date = parseDate(d.date);
         d.close = +d.close;
      });

here's a pic of the error: https://twitter.com/maggie_a_lee/status/273858397173080064/photo/1

thanks to all!!

回答1:

This related to the version of the D3 library; currently it is transitioning from v2 to v3: https://github.com/mbostock/d3/wiki/Release-Notes

The example you are working from has already been modified for v3, but you are still loading the v2 library.

For d3.tsv the difference between the two version is related to the callback signature:

v2:

d3.tsv("data.tsv", function(data) { 
  data.forEach(function(d) { 
     d.date = parseDate(d.date);
     d.close = +d.close;
  });

v3:

d3.tsv("data.tsv", function(error, data) { 
  data.forEach(function(d) { 
     d.date = parseDate(d.date);
     d.close = +d.close;
  });

That means that in your case the actual data got stored in the error argument.