【发布时间】:2015-02-20 03:22:14
【问题描述】:
我正在结合 AngularJS 更新 D3 堆叠条形图。在这种情况下,所有数据最初都是可见的,并且更新会过滤掉不需要的数据。在过去,使用此模型可以毫无问题地工作:
data = [{
name: John Doe,
splits: [{distance: 1, time: 1234},]
},...]
现在我正在尝试使用此模型为每个堆栈再添加一个柱:
data = [{
name: John Doe
time: 12345,
splits: [{distance: 1, time: 1234},]
},...]
我的问题是更新数据。我的计算值已正确重新计算,例如用于缩放的域。 time update 的一行仍然只识别更新前的数据值(为简洁起见,代码 sn-p 被严重截断):
// 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,它说明了与我的脚本中相同的错误。所有代码都是直接从显示问题的脚本中提取的。底部的间隔更新模拟了通常会发生的数据交换。
【问题讨论】:
-
你有小提琴吗?
-
现在做一个小提琴。
-
我刚刚在问题底部添加了一个 JSFiddle
标签: javascript html d3.js bar-chart