这是问题here的后续问题。
我想使用 d3.csv
和 d3.json
加载多个数据集,然后使用 d3.zip
组合这些数据集。在下面的例子中我只使用了两个。第一个数据集将存储在 xyData
中,第二个数据集将存储在 colData
中。我的目标是调用类似
var combinedData = d3.zip(colData, xyData);
但是,由于这些数据集只能分别在 d3.csv
和 d3.json
范围内访问,因此这是行不通的。有什么解决方法吗?如果要加载更多数据集,人们将如何处理?
第一个数据集如下所示:
//xyData.csv
x,y
0,0.00e+000
0.6981317,6.43e-001
1.3962634,9.85e-001
我的 JSON
数据集如下所示:
//colData.json
{
"el1": [
{"color": "green"},
{"color": "purple"},
{"color": "brown"}
],
"el2": [
{"color": "black"},
{"color": "red"},
{"color": "yellow"}
],
"el3":[
{"color": "brown"},
{"color": "yellow"},
{"color": "blue"}
]
}
我读取这些数据集的方式如下:
//using foreach
var xyData = [];
d3.csv("xyData.csv", function(myData) {
myData.forEach(function(d) {
d.x = +d.x; //convert data to numbers
d.y = +d.y;
});
console.log(myData[1]);
xyData = myData;
console.log(xyData[1])
});
console.log(xyData) //this will be an empty array
//loading the json data
var colData = [];
d3.json("colData.json", function(error, jsonData) {
if (error) return console.warn(error);
colData = jsonData;
console.log(colData)
console.log(colData.el1[0])
});
console.log(colData) //this will be an empty array
//my goal would be:
//var combinedData = d3.zip(colData, xyData);
我的 console.log
如下所示:
Array [ ]
Array [ ]
Object { x: 0.6981317, y: 0.643 }
Object { x: 0.6981317, y: 0.643 }
Object { el1: Array[3], el2: Array[3], el3: Array[3] }
Object { color: "green" }
这表明加载数据按预期进行。但由于这些数据加载器的异步特性,将它们存储为全局变量是行不通的(因此,这两个数组仍然是空的)。
我的问题是:将两个数据集合并为一个数据集的最佳方法是什么?
最佳答案
D3.js 实际上可以处理 JavaScript 对象而不是文件。如果将文件名替换为 D3.json(myData){...} 存储对象的变量名(比如说,JSON 数据数组),它将可以访问该数据。
假设我们正在使用 jQuery,并且我们还包含一个名为 Papa Parse 的帮助程序库(它使生活更轻松)。
第 1 步. 将 CSV 数据转换为 JSON 数据并将其存储在变量 A 中:
var A = Papa.parse(yourCSV);
第 2 步:读取 JSON 数据并将其存储在名为 B 的变量中
var B;
$(document).ready(function() {
$.getJSON('yourJSON.json', function(json){
B = json;
});
});
第 3 步:将数据集 A 和 B 合并到变量 C 中 重要提示:在我们稍后将其提供给 D3 之前,您可能需要格式化存储在 A 中的 CSV json,以查看您期望的外观
var C={};
$.extend(C, A, B);
第 4 步:将 C 赋予 D3
d3.json(C, function(error, jsonData) {
// Use data here to do stuff
});
我在自己的项目中使用了上述内容作为解决方法。
您也许可以尝试在 D3.csv 中调用 D3.json,但我之前没有尝试过:
d3.csv("A.csv", function(errorA, dataA) {
d3.json("B.json", function(errorB, dataB) {
// Use data to do stuff
});
});
关于javascript - 如何加载 CSV 和 JSON 文件并使用 d3.json、d3.csv 和 d3.zip 将两个数据集合并为一个数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32380755/