您好我是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 :(得分: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>
&#13;