javascript d3 使用退出删除数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15230574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:59:32  来源:igfitidea点击:

d3 remove data using exit

javascriptd3.js

提问by jon37

I've prepared a small fiddle to illustrate the problem here

我准备了一个小小提琴来说明这里的问题

I'm having an issue using d3's exit function to remove elements from the dom.

我在使用 d3 的退出函数从 dom 中删除元素时遇到问题。

Say I have an array of 10 elements:

假设我有一个包含 10 个元素的数组:

var data = [1 ,4, 5, 6, 24, 8, 12, 1, 1, 20]

I use this data to create a simple horizontal bar chart using d3

我使用这些数据使用 d3 创建一个简单的水平条形图

d3.selectAll('rect') 
.data(data) 
.enter() 
.attr("class", "rectangle")
.attr("stroke", "black")
.attr("stroke-width","1px")
.attr("fill","none")
.attr("x", 0)
.attr("y", function(d, i) { return 25 * i; } )
.attr("width", function(d) { return 22 * d; } )
.attr("height", "20");

Now after a short delay I'd like to prune my dataset so all that I have left is

现在经过短暂的延迟,我想修剪我的数据集,所以我剩下的就是

var truncatedData = [4,5]

d3.selectAll('rect')
    .data(truncatedData )   
    .exit()
    .transition()
    .delay(3000)
    .remove();

Data is removed successfully but it still shows the first two elements 1,4 instead of 4,5.

数据已成功删除,但仍显示前两个元素 1,4 而不是 4,5。

How can I remove all but [4,5] from the dom?

如何从 dom 中删除除 [4,5] 之外的所有内容?

回答by Lars Kotthoff

By default, d3 matches elements given to .data()by their index and not value. That is, giving it a two-element array in the second call means that the first two elements from the first call (indices 0 and 1) are retained.

默认情况下,d3 匹配.data()由它们的索引而不是值给出的元素。也就是说,在第二次调用中给它一个双元素数组意味着保留第一次调用的前两个元素(索引 0 和 1)。

To fix this issue in your case, give a function to match elements to the second call to .data(), i.e.

要在您的情况下解决此问题,请提供一个函数以将元素与第二次调用相匹配.data(),即

.data([5, 6], function(d) { return(d); })

Fixed jsfiddle here.

在这里修复了 jsfiddle 。