d3.js
通过获取100个对象的数组来绘制一系列矩形。尽管console.log(data)
显示正在检索新数据,但新数据点似乎未附加任何矩形。
被.enter().append()
不正确地使用?
function init() {
var width = 800,
height = 400,
margin = 50;
chart = d3.select('#chart')
.append('svg:svg')
.attr('width', width)
.attr('height', height);
}
function do_update() {
data = fetch_latest_top100();
console.log(data)
chart.selectAll('rect')
.data(data)
.enter()
.append('svg:rect')
.attr('x', function(d) { return x(d.x); })
.attr('y', function(d) { return y(d.y); })
.attr('height', function(d) { return d.value; })
.attr('width', function(d) { return 3 });
}
jsfiddle:http : //jsfiddle.net/BU8cA/
您的update方法的问题在于它仅处理新元素,并且不更新现有元素以匹配其新数据。使用enter()选择创建新矩形后,必须返回到完整选择(新矩形和不断变化的矩形)以设置将要更改的属性。
最简单的方法是将选择内容存储在变量中,该变量已在您应用数据功能的那一点,但在调用enter方法之前,如下所示:
var rects = chart.selectAll('rect')
.data(data);
rects.enter()
.append('svg:rect')
.attr('width', function(d) { return 3 });
// since the width is constant, you only need to set it once
rects.exit().remove(); //if the number of data points might shrink
rects.attr('x', function(d) { return x(d.x); })
.attr('y', function(d) { return y(d.y); })
.attr('height', function(d) { return d.value; });
//note that this now includes the rectangles created with enter()
//as well as the old ones you are resizing / repositioning
那应该获得正确的数据,但是您仍然存在布局问题(无论如何,摆在小提琴上),因为您的y值设置不正确。y值是矩形顶部的位置,因此,如果您希望看起来像所有的条都位于同一行上,则需要根据条的高度对其进行调整。Mike Bostock的教程和演示在这里:http : //bost.ocks.org/mike/bar/3/
D3版本4+的更新
附加到“输入”选择中的元素不再自动添加到主(更新)选择中。现在,您需要通过merge
在“输入”选择上调用方法来显式创建“合并”选择:
var rects = chart.selectAll('rect')
.data(data);
rects.exit().remove(); //if the number of data points might shrink
rects.enter()
.append('svg:rect')
.attr('width', function(d) { return 3 }) // since the width is constant, you only need to set it once
.merge(rects)
//merge the newly added elements into the main selection
//of existing elements to update
.attr('x', function(d) { return x(d.x); })
.attr('y', function(d) { return y(d.y); })
.attr('height', function(d) { return d.value; });
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句