2017-03-02 6 views
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を使用してきており、かなり快適に感じています。しかし、私はv4のいくつかの異なる動作を理解するのが非常に苦労しています。

答えて

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を使用する場合は、唯一の既存の要素が選択されています。次に、入力することによって、新しい選択を生成する新しい要素を作成しています。すべてを更新する必要がある場合は、新しい要素と既存の要素を1つの選択項目にマージするだけです。その選択から

は、私は単純に選択されたすべての .circle(単一選択 - 一つの要素 gごと)し、その後 .each呼び出しを行ってから私を防ぎ結合APIに半径感謝を更新します。私はこれら2つがどのように比較されるかは分かりませんが、私はいつもそうしました。

最後に、hereはパターンを示すbl.ocksです。

+0

ありがとうございます!これは実際に動作します。選択されたマージがトリックでした。私はそのパターンを知らなかった。再度、感謝します! – turtle

+0

大歓迎!私は最近これにも直面した –

関連する問題