score:2

Accepted answer

d3 json function is asynchronous. so your code to create the line is executed before the json data actually arrived. you need to move the line creation code into the json function:

d3.json("https://api.myjson.com/bins/53grr", function(error, data) {

    // log the returned object on console unless error
    if (error) return console.error(error);
    console.log(data);

    var days = data.data.weather;

    // step through each day
    days.foreach(function(d) {

        // step through each hour
        d.hourly.foreach(function(h) {
            dailyraintotal = dailyraintotal + parsefloat(h.precipmm);
        });

        // add data to day
        day = {date: new date(d.date), rain: dailyraintotal.tofixed(2)};
        // push day to results array
        linedata.push(day);

        // reset the total
        dailyraintotal = 0;
    });

  var vis = d3.select("#visualisation"),
  width = 600,
  height = 250,
  margins = {
    top: 20,
    right: 20,
    bottom: 20,
    left: 50
  },
xrange = d3.time.scale().range([margins.left, width - margins.right]).domain([d3.min(linedata, function (d) {
    return d.date;
  }),
  d3.max(linedata, function (d) {
    return d.date;
  })
]),

yrange = d3.scale.linear().range([height - margins.top, margins.bottom]).domain([d3.min(linedata, function (d) {
    return d.rain;
  }),
  d3.max(linedata, function (d) {
    return d.rain * 1.2;
  })
]),

xaxis = d3.svg.axis()
  .scale(xrange)
  .ticksize(5),

yaxis = d3.svg.axis()
  .scale(yrange)
  .ticksize(5)
  .orient("left");

vis.append("svg:g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + (height - margins.bottom) + ")")
  .call(xaxis);

vis.append("svg:g")
  .attr("class", "y axis")
  .attr("transform", "translate(" + (margins.left) + ",0)")
  .call(yaxis);

var linefunc = d3.svg.line()
  .x(function (d) {
    return xrange(d.date);
  })
  .y(function (d) {
    return yrange(d.rain);
  })
  .interpolate('linear');

vis.append("svg:path")
  .attr("d", linefunc(linedata))
  .attr("stroke", "blue")
  .attr("stroke-width", .5)
  .attr("fill", "none");
});

Related Query