简体   繁体   English

如何从D3中的CSV中加载的CSV子集中一列

[英]How to subset a column from loaded in CSV in D3 javascript from

We have some data.csv 我们有一些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: 我们尝试使用D3操纵数据,并加载数据:

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. 我正在尝试重新创建以下D3块 ,这非常简单。 The only difference: I am loading in CSV data rather than the simple one-dimensional array in the example code. 唯一的区别是:我正在加载CSV数据,而不是示例代码中的简单一维数组。

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. 在Chrome开发人员中运行它,您将在第60行到达无法读取的属性“长度”,未定义错误,我将数据绑定到pie()函数。

My Questions: 我的问题:

  • Am I loading the csv data in properly? 我是否可以正确加载csv数据?
  • How can I subset the Total column only for use as values in the pie() function? 如何将Total列作为子集,仅用作pie()函数中的值? 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. 请查看mbostock对另一个问题的回答,以了解原因。

Add the code for creating the representation within the callback function of the d3.csv method. 在d3.csv方法的回调函数中添加用于创建表示形式的代码。

To use the Total column for the values you can use the value method of the pie layout like this: 要将总计列用作值,可以使用饼图布局value方法,如下所示:

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

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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