D3.js不更新数据

DFe*_*her 6 html javascript bar-chart d3.js

我正在与AngularJS一起更新D3堆叠条形图.在此,所有数据最初都是可见的,并且更新过滤掉不需要的数据.在过去,它使用这个模型没有问题:

data = [{
    name: John Doe, 
    splits: [{distance: 1, time: 1234},]
},...]
Run Code Online (Sandbox Code Playgroud)

现在我尝试使用此模型为每个堆栈添加一个栏:

data = [{
    name: John Doe
    time: 12345, 
    splits: [{distance: 1, time: 1234},]
},...]
Run Code Online (Sandbox Code Playgroud)

我的问题是更新数据.我的计算值会被正确重新计算,例如缩放域.time更新行仍然只能识别更新前的数据值(为简洁起见,代码片段被严重截断):

// 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); });
Run Code Online (Sandbox Code Playgroud)

由于这些错误,更新的列表示错误的数据并产生错误的可视化.我一整天都在盯着/测试,试图将问题与我现在的问题隔离开来.对D3更有经验的人能给我一些见解吗?

注意:对于那些感兴趣的人,这是一个Angular指令,我在其中$watch更改数据值,尽管我100%确定这不是问题.

编辑

这是一个JSFiddle,它说明了与我的脚本中相同的错误.所有代码都是直接从显示问题的脚本中提取的.底部的间隔更新模仿了通常会发生的数据交换.

scn*_*iro 2

我玩了一下你的例子并做了一些可能有用的更改。

首先,我将您的 global 重构var到您的函数内部updatex通过这样做,我们就不会在和y轴离开的地方“双重追加” 。这似乎是在旧图表之上绘制我们的图表。

然而,解决这个问题后,我得到了覆盖在旧图表之上的新图表。为了解决这个问题,我调用d3.selectAll("svg > *").remove();内部update删除所有附加的 SVG 元素和分组,为我们提供了一个“干净的石板”来渲染我们的新图表。这样就解决了重叠的问题。

您提到这是为了简洁起见而缩短的,所以我希望这个示例可以帮助您的实际应用


更新了小提琴