【发布时间】:2017-11-23 12:06:30
【问题描述】:
我正在尝试使用 D3.js 构建一种实时图表。代码可在https://plnkr.co/edit/hrawv8CTBIsJf2QWTBMb?p=preview 获得。
源数据代表来自不同组织的用户认证结果。每个组织都有一个名称、正常计数和失败计数。图表应根据数据动态更新(循环获取数据)。
代码基于https://bl.ocks.org/mbostock/3808234。
很少有问题和我不确定的事情。
exit 函数仅根据数据更新选择红条:
// JOIN new data with old elements
// specify function for data matching - correct?
var boxes = svg.selectAll(".box").data(data, function(d) {
return d.inst_name;
});
// EXIT old elements not present in new data
// this works somehow strange
// it does select all red boxes
boxes.exit().transition(t).remove();
为什么 exit() 只选择红条而不是全部?根据我的理解,d3 文档 exit() 应该只选择没有任何新数据的元素。在无限循环和常量数据文件的情况下,这不应该是所有的酒吧吗?
这显然大大破坏了图表(参见 plunker)。我需要退出来仅选择数据文件中不再可用的条形图。请参见下面的示例。
数据文件的初始状态:
inst_name,ok,fail
inst1,24,-1
inst2,23,-3
...
数据文件的更新状态:
inst_name,ok,fail
inst1,26,-1
inst14,22,-4
...
当数据更新时,inst2 的初始状态条(蓝色和红色)应该被移除(并替换为 inst14 的数据)。为什么这不起作用?
我读过,新数据使用索引与旧数据匹配。我已指定应使用 inst_name:
var boxes = svg.selectAll(".box").data(data, function(d) {
return d.inst_name;
});
这有必要吗(我在插入数据的时候到处都用过)?
移除元素的过渡也不起作用。有什么问题?
我也不确定添加新柱时是否需要指定数据:
var boxes = svg.selectAll(".box").data(data, function(d) {
return d.inst_name;
});
.....
// add new element in new data
svg.selectAll(".blue")
.data(data, function(d) { // is this necessary ?
return d.inst_name;
}) // use function for new data matching against inst_name, necessary?
.enter().append("rect")
.transition(t)
.attr("class", function(d) {
return "blue box "
})
.attr("x", function(d) {
return x(d.inst_name);
})
.attr("width", x.bandwidth())
.attr("y", function(d) {
return y(d.ok);
})
.attr("height", function(d) {
return height - y(d.ok + min);
})
感谢您的帮助。
编辑
底层数据被脚本改变(这在原帖中没有写清楚),所以它可以独立于图状态改变。数据应该只会增长。
【问题讨论】:
标签: javascript csv d3.js