带有JSON Web服务的D3图表

我正在尝试从本教程中制作以下条形图 。 本教程使用TSV文件,但是我已经修改了JSON的代码。 我已经检查了我创build的Node / Express服务中的端点http://localhost:3000/graphs/data确实返回了JSON,这可以在下面看到。 也包括适当的D3库。 检查了所有这些之后,我无法得到图表来呈现。

目标是在x轴上有route并在y轴上count 。 任何build议将不胜感激。

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.csv()不同, d3.csv()只接受两个参数,第二个参数是callback函数。 你的来电

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

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

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