Hard Fitness
Hard Fitness

Reputation: 452

Error parsing d3 line chart JSON data

Having issues with getting JSON data on a line chart, i can do this for a bar chart totally fine but for some reason it gives me an error when doing a line chart. There isn't much documentation around so see if anyone knows.

I get this error

Error: Problem parsing d="MNaN,400LNaN,258.65447419986936LNaN,221.90289571086436LNaN,183.32244720226433LNaN,134.29131286740693LNaN,149.70607446113652LNaN,63.1395602003048LNaN,37.44829087742215LNaN,69.40997169605924LNaN,0LNaN,169.91073372523405LNaN,643.2397126061397"

JSON data is as follows:

[{"logins":"3333","month_name":"January"},{"logins":"4956","month_name":"February"},{"logins":"5378","month_name":"March"},{"logins":"5821","month_name":"April"},{"logins":"6384","month_name":"May"},{"logins":"6207","month_name":"June"},{"logins":"7201","month_name":"July"},{"logins":"7496","month_name":"August"},{"logins":"7129","month_name":"September"},{"logins":"7926","month_name":"October"},{"logins":"5975","month_name":"November"},{"logins":"540","month_name":"December"}]

Now the code:

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

Anyone know how to fix it so it displays the line chart?

Upvotes: 1

Views: 800

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109252

You need to parse your dates and pass in the numbers as numbers:

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

If you run this code just after loading the JSON, everything should work fine.

Upvotes: 1

Related Questions