0
在版本d3 v3中,我的一個常見工作流程是創建幾個svg組元素,然後爲每個g添加一些其他子元素。作爲一個例子,下面我創建了3個組元素,併爲每個組附加了一個圓。然後我用selection.each
方法來更新每個圓的半徑:使用嵌套元素難以理解d3版本4選擇生命週期
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很長一段時間,感覺很舒服。但是,我很難理解第4版中的一些不同行爲。
非常感謝!這確實有效。合併後跟選擇是訣竅。我不知道這種模式。再次感謝! – turtle
最受歡迎!我最近也遇到過這個問題 –