【问题标题】:data is undefined after importing from a csv file with d3使用 d3 从 csv 文件导入后数据未定义
【发布时间】:2015-05-24 19:43:50
【问题描述】:

我用 d3 和一个 json 文件绘制了一张世界地图,并试图根据我的数据在地图上绘制圆圈。

我使用d3.csv() 函数导入了我的数据,如下所示。但是,data 似乎无法识别我的功能 function plot_points(data)。当我在函数的控制台中输入data 时,它一直告诉我data is undefined。这很有趣,因为我之前在另一个项目中使用了完全相同的代码,data 将被识别为对象数组。你能说出什么问题吗?

<head>
    <script type="text/javascript">
      function draw(geo_data) {
        "use strict";
        var margin = 75,
            width = 1400 - margin,
            height = 600 - margin;

        d3.select("body")
                .append("h2")
                .text("Circle Graph");

        var svg = d3.select("body")
            .append("svg")
            .attr("width", width + margin)
            .attr("height", height + margin)
            .append('g')
            .attr('class', 'map');

        var projection = d3.geo.mercator()
                               .scale(150)
                               .translate([width / 2, height / 1.2]);

        var path = d3.geo.path().projection(projection);

        var map = svg.selectAll('path')
                     .data(geo_data.features)
                     .enter()
                     .append('path')
                     .attr('d', path)
                     .style('fill', 'lightBlue')
                     .style('stroke', 'black')
                     .style('stroke-width', 0.5);

        // debugger;
        // here data is undefined
        function plot_points(data) {
            // debugger;
            // here data is undefined as well
        };

        d3.csv("data/olympics_editions.csv", function(d) {
          // debugger;
          // here d is each data point/object, and seems to be working just fine
          d['Year'] = format.parse(d['Year']);
          d['Latitude'] = +d['Latitude'];
          d['Longitude'] = +d['Longitude'];
          return d;
        }, plot_points);

      };
    </script>
  </head>
  <body>
    <script type="text/javascript">
      d3.json("data/world_countries.json", draw);
    </script>
  </body>

【问题讨论】:

  • 您是否遇到任何错误?
  • @LarsKotthoff 我收到了一些关于.length 的错误,不能在null 上使用,但它以某种方式消失了。现在我想我知道为什么它不能正确读取数据了,因为正如 Josh 在下面建议的那样,to d3 读取 csv 文件的语法不同于读取 json 或 tsv 文件。

标签: javascript csv d3.js data-visualization


【解决方案1】:

从 d3.csv 文档中,回调的签名如下:

function(error, rows) {

});

尝试将error 参数添加到您的 plot_points 函数:

function plot_points(error,data) {

};

【讨论】:

  • Josh 是对的,但我正在为此添加一些细节,希望将来可以对其他人有所帮助。对于函数,它应该是函数 plot_points(data){ }。对于导入文件,它应该是 d3.csv(data/olympics_editions.csv", function(d) { return { year: d.Year, latitude: d.Latitude, longitude: d.Longitude};}, plot_points) ;
猜你喜欢
  • 2013-03-23
  • 2014-03-17
  • 2014-01-27
  • 1970-01-01
  • 2015-06-30
  • 2018-08-07
  • 2019-03-09
相关资源
最近更新 更多