2014-02-19 104 views
3

我有點困惑我需要加載多個CSV文件使用JavaScript,我需要改變每個加載的數據集的一些屬性。所以基本上我使用這個叫做d3的框架,我想加載3個csv文件,然後爲每個csv文件我需要改變爲平行座標繪圖繪製的線的顏色。目前我正在使用三個數據加載,但這會弄亂我的情節,並且我已經有了所有的價值。使用Javascript加載多個CSV文件

// load csv file and create the chart 
d3.csv('X.csv', function(data) { 
pc = d3.parallelCoordinates()("parallelcoordinates") 
    .data(data) 
    .color(color) 
    .alpha(0.4) 
    .render() 
    .brushable() // enable brushing 
    .interactive() // command line mode 

var explore_count = 0; 
var exploring = {}; 
var explore_start = false; 
pc.svg 
    .selectAll(".dimension") 
    .style("cursor", "pointer") 
    .on("click", function(d) { 
     exploring[d] = d in exploring ? false : true; 
     event.preventDefault(); 
     if (exploring[d]) d3.timer(explore(d,explore_count,pc)); 
}); 

我正在做上述三次。現在發生的情況是,所有的數據都繪製在同一個圖上,但是這些數據重疊(基本上它的三個圖相互重疊)。我想整合它,我認爲最好的方法是巧妙地加載JS文件並以某種方式操縱它。雖然我不知道。有人會告訴我我將如何實現這一目標?

+0

我會將這三個文件加載到三個對象數組中,並將它們連接起來,然後將它們傳遞給D3 – dandavis

回答

7

這個線程將是有益的:https://groups.google.com/forum/#!msg/d3-js/3Y9VHkOOdCM/YnmOPopWUxQJ

從連接的最佳解決方案(IMO)是這樣的:

var rows1, rows2, remaining = 2; 

    d3.csv("file1.csv", function(csv) { 
    rows1 = csv; 
    if (!--remaining) doSomething(); 
    }); 

    d3.csv("file2.csv", function(csv) { 
    rows2 = csv; 
    if (!--remaining) doSomething(); 
    }); 

    function doSomething() { 
    // … do something with rows1 and rows2 here … 
    } 
2

你可以使用D3 queue同時加載該文件。一個例子;

d3.queue() 
.defer(d3.csv, "file1.json") 
.defer(d3.csv, "file2.json") 
.defer(d3.csv, "file3.json") 
.await(function(error, file1, file2, file3) { 
    if (error) { 
     console.error('Oh dear, something went wrong: ' + error); 
    } 
    else { 
     doSomeStuff(file1, file2, file3); 
    } 
});