解析d3折线图JSON数据时出错

时间:2014-01-06 20:26:06

标签: javascript php json d3.js

在折线图上获取JSON数据存在问题,我可以对条形图完全没问题,但由于某种原因,在做折线图时它会给我一个错误。没有太多的文档,所以看看是否有人知道。

我收到此错误

  
    

错误:问题解析d =" MNaN,400LNaN,258.65447419986936LNaN,221.90289571086436LNaN,183.32244720226433LNaN,134.29131286740693LNaN,149.70607446113652LNaN,63.1395602003048LNaN,37.44829087742215LNaN,69.40997169605924LNaN,0LNaN,169.91073372523405LNaN,643.2397126061397&#34 ;

  

JSON数据如下:

  
    

[{"登录":" 3333"" MONTH_NAME":" 1"},{"登录&#34 ;:" 4956"" MONTH_NAME":"二月"},{"登录":" 5378",& #34; MONTH_NAME":"三月"},{"登录":" 5821"" MONTH_NAME":"四月"},{"登录":" 6384"" MONTH_NAME":"五月"},{"登录& #34;:" 6207"" MONTH_NAME":" 6月"},{"登录":" 7201" " MONTH_NAME":" 7月"},{"登录":" 7496"" MONTH_NAME":&# 34; 8月"},{"登录":" 7129"" MONTH_NAME":" 9月"},{&#34 ;登录":" 7926"" MONTH_NAME":" 10月"},{"登录":" 5975&# 34;," MONTH_NAME":"十一月"},{"登录":" 540"" MONTH_NAME&#34 ;: "腊"}]

  

现在代码:

  var margin = {top: 20, right: 20, bottom: 30, left: 40},    
    width = $("svg").parent().width();
    height = $("svg").parent().height();
    aspect = 500 / 950;
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.month_name); })
    .y(function(d) { return y(d.logins); });

var svg = d3.select(document.createElement("div")).append("svg")

    .attr("preserveAspectRatio", "xMidYMid")
    .attr("viewBox", "0 0 950 500")
    .attr("width", width)
    .attr("height", width * aspect)
    .attr("id", "art_chart")
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    x.domain(d3.extent(data, function(d) { return d.month_name; }));
    y.domain(d3.extent(data, function(d) { return d.logins; }));
         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("Logins");

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

任何人都知道如何修复它以显示折线图?

1 个答案:

答案 0 :(得分:1)

您需要解析日期并将数字作为数字传递:

data.forEach(function(d) {
  d.month_name = d3.time.format("%B").parse(d.month_name);
  d.logins = +d.logins;
});

如果在加载JSON之后运行此代码,一切都应该正常工作。