D3.js:根据数据设置轴位置

时间:2016-03-03 11:18:48

标签: javascript json d3.js svg

我正在尝试根据染色体数据在一个svg图像中绘制多个图形。目的是为每条染色体绘制1个图。我想根据de数据中的染色体编号转置轴(和数据)。

数据条目如下所示(在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 个答案:

答案 0 :(得分:1)

这里有一行:

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

不足以为每条染色体创建一个轴。一种方法(可能不是最简单的,但非常“d3友好的”)是创建一个代表你的染色体组的数组。

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
     });