我正在尝试根据染色体数据在一张 svg 图像中绘制多个图形。目的是为每条染色体绘制一张图。我想根据数据中的染色体编号转置轴(和数据)。
数据条目如下所示(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 图像。
有人知道我哪里出错了吗?
最佳答案
这里的行:
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.
现在您将此列表绑定(bind)到您的轴,以便为每个元素创建一个轴:
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
});
关于javascript - D3.js:根据数据设置轴位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35770740/