2016-03-03 82 views
0

我想根據染色體數據在一個svg圖像中繪製多個圖形。目的是爲每個染色體繪製1個圖。我想根據de數據中的染色體數目轉置座標軸(和數據)。D3.js:根據數據設置軸位置

數據條目看起來像這樣(以JSON):

 
[{ 
    "chrom": 1, 
    "pos": 2000000, 
    "ratio": 0.0253, 
    "average": 0.0408, 
    "stdev": 0.0257, 
    "z-score": - 0.6021 
}, { 
    "chrom": 1, 
    "pos": 2250000, 
    "ratio": 0.0304, 
    "average": 0.0452, 
    "stdev": 0.0245, 
    "z-score": - 0.6021 
}, { 
    "chrom": 1, 
    "pos": 2500000, 
    "ratio": 0.0357, 
    "average": 0.0498, 
    "stdev": 0.024, 
    "z-score": - 0.5885 
}, { 
    "chrom": 1, 
    "pos": 2750000, 
    "ratio": 0.0381, 
    "average": 0.0522, 
    "stdev": 0.0228, 
    "z-score": - 0.6146 
}, 
{etc..} 

目前我的代碼看起來是這樣的:

 

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

     x.domain(d3.extent(data, function(d) { return d.pos; })); 
     y.domain(d3.extent(data, function(d) { return d['ratio']; })); 


     svg.append("g") 
     .attr("class", "x axis") 
     .data(data) 
     //.attr("transform", "translate(0," + graph_height + ")") 
     .attr('transform', function(d) { 
     if (d.chrom > Math.ceil(chrnumber/2)) { 
      console.log('translate('+ graph_width + graph_margin.center + ',' + graph_height + d.chrom * (graph_height + graph_margin.top) + ')'); 
      return 'translate('+ graph_width + graph_margin.center + ',' + graph_height + d.chrom * (graph_height + graph_margin.top) + ')'; 
     }else { 
      console.log('translate(0,' + graph_height + d.chrom * (graph_height + graph_margin.top) + ')'); 
      return 'translate(0,' + graph_height + d.chrom * (graph_height + graph_margin.top) + ')'; 
     } 
     }) 
     .call(xAxis); 
    }); 

但是,這產生了任何錯誤,也沒有任何輸出。我想上面的代碼中有一些錯誤,因爲svg圖像不是在頁面上生成的。

有沒有人有我的錯誤的想法?

回答

1

這裏的線路:

svg.append("g") 
    .attr("class", "x axis") 
    .data(data) 

是不夠的,每創造一個染色體軸。一種方法(可能不是最簡單的方法,但是一種非常友好的方法)是創建一個代表您的染色體集合的數組。

var chromList = d3.set(     //data structure removing duplicates 
        data.map(function(d) { // create a list from data by ... 
        return d.chrom  // ...keeping only the chrom field 
        }).values();   // export the set as an array 
    //chromList=[1,2,3 ..], according to the values of chrom seen in your data. 

現在這個名單綁定到軸,以創建每個元素的一個軸:

svg.append("g")  //holder of all x axis 
    .selectAll(".axis") //creates an empty selection at first, but it will be filled next. 
    .data(chromList) //bind the list of chrom ids to the selection 
    .enter()   //the selection was empty, so each chromosome is "entering" 
    .append("g")  //for each chromosome, insert a g element: this is the corresponding axis 
    .attr("class", "x axis") 
    .attr('transform', function(d) { 
     //use d here as your chromosome identifier 
    }); 
+0

給予好評的好的解釋。然而,解決方案對我無效。我編輯了我的代碼,但仍然沒有輸出:/ –

+0

好的,更正。該解決方案似乎工作順利!我現在遇到的問題是,D3試圖爲json中的每個條目繪製一個新的軸,從而在同一位置產生1000 + x軸。你有解決這個問題嗎? D3有一個函數來檢查一個元素是否已經存在? 感謝您的幫助! –

+0

對,我的錯誤,我認爲數據實際上是一個染色體列表,這顯然是錯誤的。我要編輯它。 – tarulen