具有 JSON 网络服务的 D3 图表

D3 chart with JSON web service

我正在尝试制作以下内容bar chart from this tutorial。本教程使用 TSV 文件,但我修改了 JSON 的代码。我检查过我创建的节点/Express 服务的端点 http://localhost:3000/graphs/data 确实返回了 JSON,如下所示。适当的 D3 库也包括在内。检查完所有这些后,我无法渲染图表。

目标是 route 在 x 轴上,count 在 y 轴上。任何建议将不胜感激。

JSON 响应

[{"route":"9","count":273},{"route":"49","count":242},{"route":"151","count":221},{"route":"8","count":220},{"route":"3","count":213},{"route":"82","count":209},{"route":"79","count":206},{"route":"N5","count":206},{"route":"62","count":206},{"route":"4","count":202}]

条形图代码

<script>

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

var formatPercent = d3.format(".0%");

var x = d3.scale.ordinal()
    .rangeRoundBands([0, width], .1);

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 tip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(d) {
    return "<strong>Count:</strong> <span style='color:red'>" + d.count + "</span>";
  })

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 + ")");

svg.call(tip);

d3.json('http://localhost:3000/graphs/data', type, function(error, data) { 
  x.domain(data.map(function(d) { return d.route; }));
  y.domain([0, d3.max(data, function(d) { return d.count; })]);

  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("Frequency");

  svg.selectAll(".bar")
      .data(data)
    .enter().append("rect")
      .attr("class", "bar")
      .attr("x", function(d) { return x(d.route); })
      .attr("width", x.rangeBand())
      .attr("y", function(d) { return y(d.count); })
      .attr("height", function(d) { return height - y(d.count); })
      .on('mouseover', tip.show)
      .on('mouseout', tip.hide)

});

function type(d) {
  d.count = +d.count;
  return d;
}

</script>   

d3.json()d3.csv() 不同,只有两个参数,第二个是回调函数。您的来电

d3.json('http://localhost:3000/graphs/data', type, function(error, data) {

将调用结果传递给 type,而不是之后的匿名函数,后者永远不会执行。调用应该是

d3.json('http://localhost:3000/graphs/data', function(error, data) {