Reading json data from a file in d3.js not working

时间:2016-04-15 15:18:23

标签: javascript angularjs json d3.js

This is a d3 code that generates a line graph from data.tsv file. However I want to input data in form of json. So what will be changes required here. There is a line marked with *'s .I have changed tsv to json but the code is not working.

<script>

var margin = {top: 20, right: 20, bottom: 30, left: 50},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var formatDate = d3.time.format("%d-%b-%y");
var  x=12;
var x = d3.time.scale()
    .range([0, width]);

var y = d3.scale.linear()
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left");

var line = d3.svg.line()
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.close); });

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

d3.tsv("data.tsv", type, function(error, data) {    ///////*****/////
  if (error) throw error;

  x.domain(d3.extent(data, function(d) {   return d.date; }));
  y.domain(d3.extent(data, function(d) { return d.close; }));

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("Price ($)");

  svg.append("path")
      .datum(data)
      .attr("class", "line")
      .attr("d", line);
});

function type(d) {
  d.date = formatDate.parse(d.date);
  d.close = +d.close;
  return d;
}

</script>

1 个答案:

答案 0 :(得分:1)

首先,您必须检查您的JSON结构是否与TSV或CSV中的数据正确匹配。例如,假设这是您的CSV:

foo, bar
4, 5
12, 2
3, 61

你的JSON应该是这样的:

[
 { 
   "foo": 4,
   "bar": 5
 },
 { 
   "foo": 12,
   "bar": 2
 },
 { 
   "foo": 3,
   "bar": 61
 }
]

即,一个对象数组。有时,在非常大而复杂的JSON中,很容易忘记逗号或大括号。我使用codebeautify来检查:

http://codebeautify.org/jsonviewer

然后,只需更改d3.tsv的{​​{1}}:

d3.json

注意:与d3.json("data.json", function(data){ console.log(data); //just to check if it's all right //the rest of your code }); d3.csv相反,您无法为d3.tsv提供访问者功能。