2017-01-24 16 views
0

こんにちは私はd3を初めて使ったので、棒グラフのデータを更新できませんでした。 次のコードを使用してバーを作成しています。D3更新棒グラフ - 新しいデータをバインドできません

g.selectAll(".bar") 
.data(data) 
.enter().append("rect") 
.attr("class", "bar") 
.attr("x", function(d) { return x(d.letter) + 1; }) 
.attr("y", function(d) { return y(d.frequency); }) 
.attr("width", x.bandwidth() - 1) 
.attr("height", function(d) { return height - y(d.frequency); }) 

私は、ハードコーディングされた値を使用してデータを変更することができました:

var bar = svg.selectAll(".bar"); 

bar.transition().duration(750).data(data).enter() 
    .attr("y", function(d) { return 0; }) 
    .attr("height", function(d) { return Math.random()*100; }); 

にはどうすれば適切に新しいデータをバインドすることができますか?

+0

更新データを使用して、グラフを再描画しなければならないことを意味します。グラフを再描画する関数を作成する必要があります。あなたはその関数のデータに依存するコードを保持することができます – murli2308

+0

あなたの質問は明確ではありません。何を知りたいのですか、データを再バインドする方法、または選択肢を設定する方法は?一方、この例をS.O.ドキュメント:http://stackoverflow.com/documentation/d3.js/5749/update-pattern/20318/updating-the-data-a-basic-example-of-enter-update-and-exit-selections#t= 201701241434416574182 –

答えて

0

棒グラフをプログラムで新しいデータで更新し、プロセスに遷移アニメーションを表示する例については、次のスニペットを参照してください。

var data = [{x:10, y:10, w:50, h:25}, 
 
      {x:10, y:40, w:150, h:25}, 
 
      {x:10, y:70, w:70, h:25}]; 
 

 
var g = d3.select("g"); 
 

 
// Bind initial data to empty selection, then use enter() 
 
// to access the virtual selection from the data-join 
 
// and subsequently append a rect for each virtual selection 
 
g.selectAll(".bar") 
 
    .data(data) 
 
    .enter().append("rect") 
 
    .attr("class", "bar") 
 
    .attr("x", function(d) { return d.x; }) 
 
    .attr("y", function(d) { return d.y; }) 
 
    .attr("width", function(d) {return d.w; }) 
 
    .attr("height", function(d) { return d.h; }); 
 

 
var new_data = [{x:10, y:10, w:150, h:25}, 
 
       {x:10, y:40, w:50, h:25}, 
 
       {x:10, y:70, w:100, h:25}]; 
 

 
// Bind the new data to the rect objects. Since new_data 
 
// is of the same size as number of rects, enter() and exit() 
 
// selections from data-join will be empty and the rects 
 
// with updated bound data are now available in the default 
 
// update selection. 
 
g.selectAll(".bar") 
 
    .data(new_data) // grab the update selection by default 
 
     .transition().duration(3000) 
 
     .attr("width", function(d) { return d.w; }); // Update the attribute
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> 
 

 
<svg width="400" height="400"> 
 
    <g> 
 
    </g> 
 
</svg>

+0

作業用コードスニペットをありがとう!それは私が理解するのを助けました。 – Hangon

関連する問題