我在使用 D3.js 时面临一个特殊问题。我目前有一个类似于以下内容的数据集:
[
{ title: 'First title', dates: [ /* a lot of dates */ ] },
{ title: 'Second title', dates: [ /* a lot of dates */ ] },
// ...
]
我想每行绘制一个容器,然后在每个容器中绘制一些水滴
,每个水滴对应一个日期。
对于绘制线条容器,我有以下代码:
const dropLines = svg.selectAll('.drops').data(data, d => d.title);
dropLines.enter()
.append('g')
.attr('transform', (d, idx) => `translate(10, ${scales.y(idx)})`)
.attr('fill', configuration.eventLineColor)
.classed('drops', true);
dropLines.exit().remove();
效果很好,我得到了所有的生产线容器。
但是,我怎样才能为我的约会对象绘制水滴呢?我尝试过类似的事情:
const drop = data => {
console.log(data);
};
dropLines.enter()
// ...
.each(drop);
但是我在我的 console.log
中获得了整个数据集(带有标题)。我希望只获得当前选定的元素数据。
是否可以每行绘制我的日期?如果是这样,我怎样才能只检索当前数据和当前选择(当前行容器)?
最佳答案
您需要进行子选择。我通常使用 .each
来实现此目的:
// Note: Not .enter(), you've already handled that
dropLines.each(function(drop) {
// Now a new selection
var date = d3.select(this).selectAll('.date').data(drop.dates);
// "date" is now bound to the array of dates, proceed as usual
date.enter().append(
// ... etc
)
});
关于javascript - 是否可以每行绘制日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34090525/