我正在结合 AngularJS 更新 D3 堆叠条形图。在这种情况下,所有数据最初都是可见的,并且更新会过滤掉不需要的数据。过去,使用此模型可以毫无问题地工作:
data = [{
name: John Doe,
splits: [{distance: 1, time: 1234},]
},...]
现在,我正尝试使用此模型向每个堆栈中再添加一个条:
data = [{
name: John Doe
time: 12345,
splits: [{distance: 1, time: 1234},]
},...]
我的问题是更新数据。我的计算值重新计算正确,例如缩放域。 time
update 的一行仍然只识别更新之前的数据值(为简洁起见,代码片段被大量 chop ):
// Set ranges of values in axes
x.domain(data.map(function(d) { return d.name}));
y.domain([ min , max]);
// Y Axis is updated to the correct time range
chart.append('g').attr('class', 'y axis').call(yAxis).selectAll('text').style('font-family','Open Sans').style('font-size', '.9rem');
// data join / Select Athlete
var athlete = chart.selectAll(".athlete").data(data),
athdata = athlete.enter(),
console.log(data) // data is correct here
// add container for each athlete
athplace = athdata.append("g")
.attr("class", "athlete")
.attr("transform", function(d) { return "translate(" + x(d.name) + ",0)"; })
.text(function(d) { return d.name}),
// ENTER time
athplace.append('rect')
.attr('class', "time")
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.time.time); })
.attr("height", 0).transition().duration(300)
.attr("height", function(d) { return height-y(d.time); });
... enter splits & labels
// exit splits & athlete
splitlabels.exit().transition().duration(300).attr('opacity', 0).remove();
splits.exit().transition().duration(300).attr('height', 0).attr('opacity', 0).remove();
athlete.exit().transition().duration(300).attr('width',0).attr('opacity', 0).remove();
console.log(athlete) // data is still correct
// UPDATE time, this chain has the problem with data not being updated. "d" is equal to previous values
athlete.selectAll('rect.time')
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.time.time); })
.attr("height", function(d) { return height-y(d.time); });
由于这些错误,更新后的列代表了错误的数据并产生了错误的可视化效果。我整天都在盯着/测试这个问题,试图将问题与我现在所拥有的隔离开来。对 D3 更有经验的人可以给我一些见解吗?
注意:对于那些感兴趣的人,这一切都在 Angular 指令中,我在其中 $watch
更改数据值,尽管我 100% 确定这不是问题。
编辑
这是一个JSFiddle这说明了与我的脚本中相同的错误。所有代码都是直接从展示问题的脚本中提取的。底部的间隔更新模仿通常发生的数据交换。
最佳答案
我试了一下您的示例并做了一些可能有用的更改。
首先,我将你的全局 var
重构到你的 update
函数中。通过这样做,我们不会在 x
和 y
轴停止的地方“双重追加”。这似乎是在我们的旧图表之上绘制我们的图表。
但是,修复此问题后,我得到了覆盖在旧图表之上的新图表。为了解决这个问题,我在 update
中调用 d3.selectAll("svg > *").remove();
来删除所有附加的 SVG 元素和分组,给我们一个“clean slate”来呈现我们的新图表。这解决了重叠问题。
你提到这是为了简洁而缩短的,所以我希望这个例子对你的实际应用有所帮助
关于javascript - D3.js 不更新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27595711/