简体   繁体   中英

How to subset a column from loaded in CSV in D3 javascript from

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM