user3259040
user3259040

Reputation: 155

d3j : Remove a data set

I want to remove a curve when a checkbox is unchecked. I tried this without success:

function drawdata(fileno,draw){
    var name="circle"+fileno;
    if (draw) {
        console.log("Drawing file "+fileno+ " ("+files[fileno]+")");
        svg.selectAll(name) .data(datasets[fileno]) .enter() .append("circle")
        .attr('cx',function(a){ return xscales[xval](a[xval]); })
        .attr('cy',function(a){ return yscales[yval](a[yval]); })
        .attr('r',3)
        .style("opacity", 1)
        ;
    } else {
        console.log("removing file "+fileno);
        svg.selectAll(name).data(datasets[fileno]).exit().remove();
    }
}

The first part work well (ie if I check a checkbox the file is plotted) but when I uncheck it, it is not removed from the svg. I guess I do not understand the exit well. Can someone point out what is wrong? Thanks.

Sample jsfiddle code: http://jsfiddle.net/datavis/530h1qLw/11/#&togetherjs=Rkz5QyDgJm

Upvotes: 0

Views: 72

Answers (1)

Ben Lyall
Ben Lyall

Reputation: 1976

Update:

With the addition of the fiddle, it's pretty easy to see what is going on. When you do svg.selectAll(name) it's returning an empty selection. The reason for that is because there are no elements of circleN. circleN is not a valid DOM element, and none of them exist anyway, so the selection will fail.

If you make the following changes to your cds function you will see that your code now works:

function cds(el) {
    name = "circle" + el.id;
    if (el.checked) {
        svg.selectAll(name)
            .data(dataset[el.id])
          .enter().append("circle")
            .attr('cx', function (a) { return xscale(a[0]); })
            .attr('cy', function (a) { return yscale(a[1]); })
            .attr('r', 3)
            .attr('class', name)        
            .style("opacity", 1);
    } else {
        svg.selectAll("circle." + name).remove();
    }
} 

There are two changes of note in this function:

  1. .attr('class', name) being added to the code creating your new DOM elements. This will add a class to the circle, making the selection easier when it comes time to remove them.
  2. Updated the line that removes them to svg.selectAll("circle." + name).remove(); which will remove the circles when you uncheck the radio boxes.

Upvotes: 1

Related Questions