【问题标题】:using CSV instead of TSV data in d3.js在 d3.js 中使用 CSV 而不是 TSV 数据
【发布时间】:2016-09-13 06:58:30
【问题描述】:

我正在尝试使用Mike Bostock 提供的饼图示例,但是当我尝试将数据转换为 csv 时它不起作用,我不确定为什么?

这是一个 plnk 和违规代码;

http://plnkr.co/edit/C0bJ0gM1Q9gIGxVe0vyF?p=preview

  d3.csv("data.csv", type, function(error, data) {
  if (error) throw error;

  var path = svg.datum(data).selectAll("path")
    .data(pie)
    .enter().append("path")
    .attr("fill", function(d, i) {
      return color(i);
    })
    .attr("d", arc)
    .each(function(d) {
      this._current = d;
    }); // store the initial angles

  d3.selectAll("input")
    .on("change", change);

  var update = function() {
    d3.select("input[value=\"oranges\"]").property("checked", true).each(change);
  };

  function change() {
    var value = this.value;
    clearTimeout(update);
    pie.value(function(d) {
      return d[value];
    }); // change the value function
    path = path.data(pie); // compute the new angles
    path.transition().duration(750).attrTween("d", arcTween); // redraw the arcs
  }
});

function type(d) {
  return {
      apples: d.apples,
  oranges: d.oranges
  };
}

// Store the displayed angles in _current.
// Then, interpolate from _current to the new angles.
// During the transition, _current is updated in-place by d3.interpolate.
function arcTween(a) {
  var i = d3.interpolate(this._current, a);
  this._current = i(0);
  return function(t) {
    return arc(i(t));
  };
}

另外,您可能会猜到我是 d3 的新手。我想知道什么会更有效,使用来自 excel 文件的原始 csv 数据或将其转换为 JSON 并以这种方式将数据解析到 d3? (我知道这是主观的,只是希望获得一些意见,这对于编码问题并不重要。

感谢您的宝贵时间

【问题讨论】:

  • 我更喜欢 JSON,更容易阅读,我认为它可能更快,也许......至于转换,你为什么要转换为 csv?
  • 我也更喜欢 JSON。我可以根据我将创建的 dataviz 构建 JSON,这样更方便,但需要更多的工作。

标签: javascript csv d3.js


【解决方案1】:

您的视图无法正常工作,因为您的 CSV 错误。

CSV:逗号分隔值,没有空格。

您的 CSV 在哪里,每个逗号后都有空格。所以所有的苹果值都可以正常工作,因为它们没有空格,但对于橘子来说不起作用,因为对于初学者来说,它读取'oranges'' oranges'(注意空格)并且所有值后面也有空格。

改成这个就可以了:

apples,oranges
53277,200
28479,200
19697,200
24037,200
40245,200

http://plnkr.co/edit/P3loEGu4jMRpsvTOgCMM?p=preview

至于使用什么数据类型看这个例子:What are the relative merits of CSV, JSON and XML for a REST API?

第二个答案很好地比较了几种数据类型,例如,CSV、JSON、XML。

这是一个sn-p:

优点:

XML - 很多库,开发者都熟悉,XSLT,可以 易于由客户端和服务器(XSD、DTD)验证,分层 数据

JSON - 易于在客户端解释,紧凑的符号, 分层数据

CSV - 在 Excel 中打开(?)

缺点:

XML - 臃肿,在 JavaScript 中比 JSON 更难解释

JSON - 如果使用不当会造成安全漏洞(不要使用 eval), 并非所有语言都有库来解释它。

CSV - 不支持分层数据,您将是唯一一个这样做的人 实际上,解析有效的 csv 比大多数开发人员认为的要困难得多 文件(CSV 值可以包含新行,只要它们介于 引号等)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多