I am using array slice to page through data. When I get to the last page (which only has 7 elements instead of 10), I cannot remove the last 3 bars. .exit().remove() works on the other elements on the page, but will not work on the bars for some reason. How can I remove the bars 8-10 on the last page?
Here’s an example on jsfiddle:
http://jsfiddle.net/PMEaT/1/
Here’s the code from the jsfiddle:
var data = [1,1,1,1,1,1,1,1,6,7,3,3,3,3,3,3,3];
var chart = d3.select("body").append("svg")
.attr("class","chart")
.attr("width",440)
.attr("height",300);
var barnumber = 10;
var page = 1;
var y = d3.scale.linear()
.domain([0,10])
.range([0,300])
var viewdata = data.slice((page-1)*barnumber,page*barnumber);
var rect = chart.selectAll("rect")
.data(viewdata);
rect.enter().insert("rect")
.attr("x",function(d,i){ return i*20})
.attr("y",function(d) {return 300 - y(d);})
.attr("width", 20)
.attr("height", y);
chart.selectAll("text")
.data(viewdata)
.enter().append("text")
.attr("x", function(d,i) { return i*20+8; })
.attr("y", 290)
.text(String);
$('#next').click(function() {
page++;
viewdata = data.slice((page-1)*barnumber,page*barnumber);
redraw();
});
$('#last').click(function() {
page--;
viewdata = data.slice((page-1)*barnumber,page*barnumber);
redraw();
});
function redraw() {
rect.data(viewdata)
.transition()
.duration(500)
.attr("x",function(d,i){ return i*20})
.attr("y",function(d) {return 300 - y(d);})
.attr("width", 20)
.attr("height", y);
chart.selectAll("text")
.data(viewdata)
.transition()
.duration(500)
.text(String);
rect.exit().remove();
}
The data-operator doesn’t compute the data-join in-place; it returns a new selection. You’re not saving the result of selection.data, so your
rectselection isn’t getting updated.Rather than chaining a transition directly off of the update selection of your data-join, you need to save the data-join first:
Of course, if you’re removing the exit selection, you’ll probably also need to append to the enter selection. Otherwise, when you get to that last page and try to go back, you’ll be stuck with only 7 bars forever rather than getting back to 10.