Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3 remove data using exit

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.

Say I have an array of 10 elements:

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.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.

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

like image 344
jon37 Avatar asked Mar 05 '13 17:03

jon37


People also ask

What is and exit () in D3 JS?

exit() function in D3. js is used to remove the elements or tags which correspond to the old data or in simple words This is used to update the DIV elements that were created before with the new data given.

What does selectAll do in D3?

selectAll() function in D3. js is used to select all the element that matches the specified selector string. Parameters: This function accepts single parameter HTML tag as a parameter. Return Value: This function returns the selected elements.


1 Answers

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.

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

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

Fixed jsfiddle here.

like image 63
Lars Kotthoff Avatar answered Oct 06 '22 00:10

Lars Kotthoff