Skip to content Skip to sidebar Skip to footer

D3.js Cannot Read Property 'length' Of Undefined

I'm pretty new to d3.js and to web too. I wanted to ue a csv file to plot a line graph but I got some errors I can't really fix: Here is the code: And this ist my a part of my cs

Solution 1:

Your mistake is assuming that calling d3.csv(...) returns your CSV data.

d3.csv makes an AJAX call to load your data and then calls a callback function when that data has been loaded. Your code continues running while the data loads in the background. When you write var data = [d3.csv(...)], data doesn't contain the data loaded from your CSV file, it contains only a d3 object, and you cannot plot that.

Instead, your call to d3.csv should look something like the following:

d3.csv("refugee_data.csv", function(d) {
  return {
        date: d.Year + "/" +d.Month,
        origin: d.Origin,
        asylum: d.Asylum,
        value: +d.Value
  };
}, function(error, rows) {
  console.log(rows);
  render(rows);
});

where render is a function that d3 will call to draw your graph when the data has finished loading.

I created a render function that contained the contents of your code from the line var w = 800; to the lines beginning var y = ..., followed by the contents of the plot function. I also replaced this.selectAll with svg.selectAll, and remove the use of plot.call. The render function I wrote ended up as follows:

function render(data) {
    var w = 800;
    var h = 450;
    var margin = {
        top: 58,
        bottom: 100,
        left: 80,
        right: 40
    };
    var width = w - margin.left - margin.right;
    var height = h - margin.top - margin.bottom;

    var svg = d3.select("body").append("svg")
                .attr("id", "chart")
                .attr("width", w)
                .attr("height", h);
    var dateParser = d3.time.format("%Y/%B").parse;
    var x = d3.time.scale()
             .domain(d3.extent(data, function(d){
                var date = dateParser(d.date);
                return date;
            }))
            .range([0,width]);

    var y = d3.scale.linear()
            .domain([0, d3.max(data, function(d){
                return d.value;
            })])
            .range([height,0]);   

        //enter()
        svg.selectAll(".point")
                .data(data)
                .enter()
                    .append("circle")
                    .classed("point", true)
                    .attr("r", 2);
        //Update
        svg.selectAll(".point")
        .attr("cx", function(d){
            var date = dateParser(d.date);
            return x(date);
        })
        .attr("cy", function(d){
            return y(d.value);
        })

        //Exit()
        svg.selectAll(".point")
        .data(data)
        .exit()
        .remove();
}

After making these changes I was able to see your graph working.


Post a Comment for "D3.js Cannot Read Property 'length' Of Undefined"