這是問題here的後續問題。如何加載CSV和JSON文件,並使用d3.json,d3.csv和d3.zip將兩個數據集合併爲一個數據集
我想使用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" }
這表明加載數據按預期工作。但是,由於這些數據加載器的異步特性,將它們存儲爲全局變量不起作用(因此,這兩個數組仍然是空的)。
我的問題是:將兩個數據集合併到一個數據集的最佳方法是什麼?
見https://stackoverflow.com/questions/21842384/importing -data-from-multiple-csv-files-in-d3或使用[queue.js](https://github.com/mbostock/queue)。 –
您有經典的「如何從異步調用返回數據」問題,答案是 - 您不能。您*必須*在回調中完成所有工作,您不能在回調中設置變量,然後在回調之外進行工作。除了D3之外,你還使用其他庫嗎?哪個? jQuery可能嗎? – Tomalak
@LarsKotthoff:我看到了這個問題,應該提到它。你如何處理兩個以上的輸入文件?你會創建一個巨大的嵌套結構嗎? – Cleb