2015-08-31 32 views
0

我是D3js的新手,想要以動態的方式使用它,也就是說,基於用戶想要繪製的數據系列,我想能夠將變量傳遞給從csv文件提取時用於解析數據的函數。使用變量從csv文件中讀取數據時使用D3js

代碼段從實例我發現所有顯示讀取數據從CSV或TSV文件爲:其中指定了CSV標題/鍵

d3.tsv("data.tsv", function(error, data) { 
    if (error) throw error; 

    data.forEach(function(d) { 
    d.date = parseDate(d.date); 
    d.close = +d.close; 
}); 

x.domain(d3.extent(data, function(d) { return d.date; })); 
y.domain(d3.extent(data, function(d) { return d.close; })); 

。我想用將被傳遞給函數的變量(即,varX和varY)替換d.date和d.close,以便顯示的數據可以變化。功能結構我在想的是:

function BarChart(filePath,varX,varY,loc){ 

    //put in the code above modified to use varX and varY in place of d.date and d.close 
    //other code required to create the chart 
    } 

我已經嘗試了幾種不同的方法(使用d.varX,或者只是VARx前提),並進行了大量的閱讀在網絡上找到的東西,但一直沒能做這個工作。我不確定D3js是否意味着以這種方式使用。任何幫助將不勝感激。

謝謝。

+0

拉爾斯,謝謝你指點我的回答!我認爲我使用了錯誤的關鍵詞進行搜索。再次感謝。 – Mick

回答

0

您可以撥打那樣的funtion:

graph({height: 200, width:400, id: "ccag", xE:d3.scale.ordinal().domain(["I", " II", "III", "IV", "V"]), 
    data: [[{ x: 0, y: 109117 },{ x: 1, y: 22546 },{ x: 2, y: 29449 },{ x: 3, y: 43711 },{ x: 4, y: 26604 }],[{ x: 0, y: 7481 },{ x: 1, y: 5328 },{ x: 2, y: 10315 },{ x: 3, y: 6218 },{ x: 4, y: 4330 }]], 
    color:[["#1c3848"],["#36a8e1"]] 
    })(); 

那麼你的函數來繪製圖形:

function graph(a) { 
    return function() { 
    var margin = {top: 20, right: 20, bottom: 20, left: 35}, 
    w = a.width - margin.left - margin.right, 
    h = a.height - margin.top - margin.bottom, 
    fnum = d3.format(","); 

    //Original data 
    var ccad = a.data; 
    var stack = d3.layout.stack(); 

    //Data, stacked 
    stack(ccad); 
..... 
..... 

或者您也可以通過文件名功能:

graph({file:"newTSV.tsv"}) 

然後在你的功能:

function graph(a) { 
    return function() { 
    d3.tsv(a.file, function(data) { .... 
相關問題