1

We have some data.csv

University,Total,Females,Males,Year,Type
PortSaid,13817,6679,7138,2012,Public
PortSaid,14790,7527,7263,2013,Public
PortSaid,17295,8509,8786,2010,Public
6OctoberUniversity,12507,4297,8210,2012,Private
6OctoberUniversity,14608,5360,9248,2013,Private

We try to use D3 to manipulate the data, and load in the data:

var dataset;

d3.csv("universities_data.csv", function(data) {
    data.forEach(function(d) {
      d.Females = +d.Females;
      d.Males = +d.Males;
      d.Total = +d.Total;
      d.Year = +d.Year
    dataset = data;
    });
  });

I am trying to re-create the following D3 block, which is quite straightforward. The only difference: I am loading in CSV data rather than the simple one-dimensional array in the example code.

Run it in Chrome developer and you’ll reach a Cannot read property 'length' of undefined error at Line 60, where I bind the data to the pie() function.

My Questions:

  • Am I loading the csv data in properly?
  • How can I subset the Total column only for use as values in the pie() function? It seems that should solve the problem.
M. Momtaz Hegazy
  • 173
  • 1
  • 12

1 Answers1

1

The problem is that your dataset variable is undefined when you try to access it outside of the callback function. Check out mbostock's answer to another question for the reason.

Add the code for creating the representation within the callback function of the d3.csv method.

To use the Total column for the values you can use the value method of the pie layout like this:

var pie = d3.layout.pie()
    .value(function(d) { return d.Total; })
    .padAngle(.02);

Demo

Community
  • 1
  • 1
Jonas Petersson
  • 685
  • 1
  • 13
  • 24
  • The Demo is very generous, works. I had seen the mbostock answer linked, but still couldn't figure out the exact implementation. Thank you – M. Momtaz Hegazy May 24 '15 at 15:43