我正在尝试创建一个包含一些数据的表,然后在最后一列(最右边)创建一个图表。我有:
var columns = ['Fruit', 'Color']
var graphData = [
[6,3,3,2,5],
[18,7,6,1,0]
];
var data = [
[6,3],
['Apple', 'Red']
]
// create table
var table = d3.select("#table").append("table");
var thead = table.append("thead").append("tr");
thead.selectAll("th").data(columns).enter().append("th").text(function(d) {
return d;
});
var tbody = table.append("tbody");
var trows = tbody.selectAll("tr").data(data).enter().append("tr");
var tcells = trows.selectAll("td").data(function(d, i) { return d; })
.enter().append("td").text(function(d, i) { return d; });
// update (add a column with graphs)
thead.append("th").text('Graphs');
trows.selectAll("td.graph").data(function(d) {return [graphData[0]];})
.enter().append("td").attr("class", "graph").each(lines);
// a sparklines plot
function lines(test) {
var width = 100, height = 20;
var data = []
for (i = 0; i < test.length; i++) {
data[i] = {
'x': i,
'y': +test[i]
}
}
var x = d3.scale.linear()
.range([0, width - 10])
.domain([0,5]);
var y = d3.scale.linear()
.range([height, 0])
.domain([0,10]);
var line = d3.svg.line()
.x(function(d) {return x(d.x)})
.y(function(d) {return y(d.y)});
d3.select(this).append('svg')
.attr('width', width)
.attr('height', height)
.append('path')
.attr('class','line')
.datum(data)
.attr('d', line);
}
graphData 的每一行代表迷你图的数据,但我似乎只能重复表中的第一行...例如 [6,3,3,2,5]。第二个迷你图应来自数据 [18,7,6,1,0]。我如何正确渲染这个? (最终我将得到一个行数多于 2 行的表)。
最佳答案
在嵌套选择中,无论行如何,您始终返回 graphData
的相同元素:
trows.selectAll("td.graph").data(function(d) {return [graphData[0]];})
需要返回该行对应的元素:
trows.selectAll("td.graph").data(function(d, i) {return [graphData[i]];})
完整演示 here .
关于javascript - 当我尝试插入迷你图时,我在每一行上得到相同的图表...如何获得正确的图表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33332703/