[英]D3 update bar chart - Can't bind new data
您好,我是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; });
如何正確綁定新數據?
有關以編程方式用新數據更新條形圖並在此過程中顯示過渡動畫的示例,請參見下面的代碼段。
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 dx; }) .attr("y", function(d) { return dy; }) .attr("width", function(d) {return dw; }) .attr("height", function(d) { return dh; }); 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 dw; }); // 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.