16

我想在使用 javascript(使用 d3 库)加载之前从 CSV 文件中选择一些数据。

这就是我加载 CSV 的方式:

d3.csv("data.csv", function(csv) {
    vis.datum(csv).call(chart);
        });

这是 CSV 文件的示例:

Class,Age,Sex,Survived
First Class,Adult,Male,Survived
First Class,Adult,Male,Survived
First Class,Adult,Male,Survived
First Class,Adult,Male,Survived
First Class,Adult,Male,Survived
First Class,Adult,Female,Survived
First Class,Adult,Female,Survived
First Class,Adult,Female,Survived
Second Class,Adult,Male,Perished
Second Class,Adult,Male,Perished
Second Class,Adult,Male,Perished
Third Class,Adult,Male,Survived
Third Class,Adult,Male,Survived
Third Class,Adult,Male,Survived
Third Class,Adult,Male,Survived
Third Class,Adult,Male,Perished
Third Class,Adult,Male,Perished
Crew,Adult,Male,Perished
Crew,Adult,Male,Perished
Crew,Adult,Female,Survived
Crew,Adult,Female,Survived

例如,我只想在加载它之前选择Second ClassFirst Classd3.csv

我知道我可以删除 CSV 中的其他行,但我想创建一个函数,以便用户可以选择他想要使用的类别。我希望这有点道理。

4

1 回答 1

32

快速回答是,用于.filter()选择您想要的行,例如:

d3.csv("data.csv", function(csv) {
    csv = csv.filter(function(row) {
        return row['Class'] == 'Second Class' || row['Class'] == 'First Class';
    })
    vis.datum(csv).call(chart);
});

如果您(编码员)正在选择过滤器,这很容易。但是,如果您需要通过用户交互来选择它,您将需要构建一个更复杂的功能。假设您已将用户选择保存在名为 的对象filters中,键对应于您的行,一个选项可能如下所示:

// an example filters object
var filters = {
    'Class': ['First Class', 'Second Class'],
    'Sex': 'Female'
};

d3.csv("data.csv", function(csv) {
    csv = csv.filter(function(row) {
        // run through all the filters, returning a boolean
        return ['Class','Age','Sex','Survived'].reduce(function(pass, column) {
            return pass && (
                // pass if no filter is set
                !filters[column] ||
                    // pass if the row's value is equal to the filter
                    // (i.e. the filter is set to a string)
                    row[column] === filters[column] ||
                    // pass if the row's value is in an array of filter values
                    filters[column].indexOf(row[column]) >= 0
                );
        }, true);
    })
    console.log(csv.length, csv);
});

(你不必这样做.reduce(),但我喜欢它的干净程度。)

如果(可能是这种情况)您不想在加载时进行此过滤,而是根据用户输入动态过滤,您仍然可以使用过滤器功能,但您需要存储csv在内存中的某处并过滤它在运行中,可能在update()由用户交互触发的功能中。

于 2012-05-17T23:12:18.183 回答