2016-03-03 78 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