D3:用附加('g')更新组选择中的数据

时间:2014-11-21 22:02:32

标签: javascript d3.js

对于我的图表,我必须创建包含多个元素(line,rect,text)的组。我在这个问题中做了我的设置:D3: update data with multiple elements in a group

我定义了这样的群组:

var group = groupContainer.selectAll('g')
    .data(items);
var groupEnter = group.enter()
    .append('g');

对于每个组元素,我附加了一个rect并进行了更新(稍后刷新事件)。

// append
groupEnter.append('rect')
    .attr('class', 'item')
    .style('fill', function (d) { return d.color; })
    .attr('x', function (d) { return x1(d.x); })
    .attr('y', function (d) { return y1(d.y); })
    .attr('width', '50')
    .attr('height', '50');

//update
group.select('rect')
    .attr('x', function (d) { return x1(d.x); })
    .attr('y', function (d) { return y1(d.y); });

这个有效!现在,当我想在我的组和rect之间放置另一个组元素时,更新不再起作用。

// append
groupEnter.append('g').append('rect') // here is the change
    .attr('class', 'item')
    .style('fill', function (d) { return d.color; })
    .attr('x', function (d) { return x1(d.x); })
    .attr('y', function (d) { return y1(d.y); })
    .attr('width', '50')
    .attr('height', '50');

//update
group.select('rect')
    .attr('x', function (d) { return x1(d.x); })
    .attr('y', function (d) { return y1(d.y); });

选择group.select('rect')与之前相同。我做错了什么?

编辑:我进一步调查了我的问题。似乎更新方法具有错误的数据映射。没有group元素(工作示例),我得到了

group.select('rect')
    .attr('x', function (d) { console.log(d); return x1(d.x); })
    .attr('y', function (d) { return y1(d.y); });

输出:

第1项 第2项 第3项 第4项 第5项 第6项 第7项 第8项 第9项 第10项

对于带有group元素的版本,我只得到输出:

第2项 第2项 第4项 第4项 第6项 第6项 第8项 第8项 第10项 第10项

也会绘制一些rects,但不是全部。我猜只有2,4,6,8,10。映射有什么问题?我是否必须重新映射我的数据?

1 个答案:

答案 0 :(得分:0)

我通过添加可选的data()参数来匹配元素来管理它。

var group = groupContainer.selectAll('g')
    .data(items, function (d) { return d.id; });

当我使用额外的追加('g')时,有人可以评论为什么我需要这个可选参数进行匹配吗?