使用嵌套元素

时间:2017-03-02 16:43:52

标签: d3.js

在版本d3 v3中,我常见的工作流程是创建多个svg组元素,然后在每个g上附加一些其他子元素。例如,在下面我创建了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中的一些不同行为。

1 个答案:

答案 0 :(得分:1)

我认为您的代码可以修改如下(未经测试,如此不确定):

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一个元素),然后更新半径,这要归功于阻止我制作{{1}的绑定API打电话。我不确定这两者是如何比较的,我总是这样做。

最后,here是一个展示模式的bl.ocks。