在d3 v3版本中,对我来说,一个常见的工作流程是创建几个svg组元素,然后将许多其他子元素附加到每个组中。例如,下面我创建了3个组元素,并在每个组中添加了一个圆圈。然后使用selection.each方法更新每个圆的半径:
var data = [2, 4, 8]
var g = d3.select('svg').selectAll('.g').data(data)
g.each(function(datum) {
var thisG = d3.select(this)
var circle = thisG.selectAll('.circle')
circle.transition().attr('r', datum * 2)
})
var enterG = g.enter().append('g').attr('class', 'g')
enterG.append('circle')
.attr('class', 'circle')
.attr('r', function(d) { return d })
g.exit().remove()在d3 v4中执行此操作的正确方法是什么?我对如何最好地做到这一点感到非常困惑。下面是我正在尝试的一个示例:
var data = [2, 4, 8]
var g = d3.select('svg').selectAll('.g').data(data)
g.enter()
// do stuff to the entering group
.append('g')
.attr('class', 'g')
// do stuff to the entering AND updating group
.merge(g)
// why do i need to reselect all groups here to append additional elements?
// is it because selections are now immutable?
var g = d3.select('svg').selectAll('g')
g.append('circle')
.attr('class', 'circle')
.attr('r', function(d) { return d })
// for each of the enter and updated groups, adjust the radius of the child circles
g.each(function(datum) {
var thisG = d3.select(this)
var circle = thisG.selectAll('.circle')
circle.transition().attr('r', datum * 2)
})
g.exit().remove()提前感谢您所能提供的任何帮助。我已经使用d3 v3很长一段时间了,感觉非常舒服。然而,我很难理解v4中的一些不同行为。
发布于 2017-03-03 01:55:54
我认为你的代码可以修改如下(未测试,所以不确定):
var data = [2, 4, 8]
var g = d3.select('svg').selectAll('.g').data(data);
// do stuff to the entering group
var enterSelection = g.enter();
var enterG = enterSelection.append('g')
.attr('class', 'g');
//Append circles only to new elements
enterG.append('circle')
.attr('class', 'circle')
.attr('r', function(d) { return d })
// for each of the enter and updated groups, adjust the radius of the child circles
enterG.merge(g)
.select('.circle')
.transition()
.attr('r',function(d){return d*2});
g.exit().remove()使用第一个.selectAll时,仅选择现有元素。然后,通过输入,您将创建新的元素,从而生成新的选择。当您需要更新所有元素时,只需在单个选择中合并新元素和现有元素即可。
通过该选择,我简单地选择了所有.circle (单个选择-每个g一个元素),然后由于绑定API阻止我进行.each调用,所以更新了radius。我不确定这两个如何比较,我只是一直这样做。
最后,here是一个演示该模式的bl.ocks。
https://stackoverflow.com/questions/42561114
复制相似问题