Reputation: 2115
I'm working on a bar graph. It shows flu vaccination rate by state. By clicking on the legend, you can switch between demographies in each state, great!
However, it takes a double click on the legend to redraw. One click successfully kills the bars, but it takes a second click to redraw them.
Working example is here. I think I'm calling my functions in the wrong order?
http://bl.ocks.org/greencracker/862062268ab398df4757
roughly, its:
declarations
d3.json (read in json){
coerce data into numbers
draw(input)
}
function draw (input) {
draw bars here
draw legend here
legend.on("click", function (d) {return do_two_things(d);)
}
function kill() {
svg.selectAll(".bar")
.remove()
}
function do_two_things(input) {
kill();
draw(input);
}
Upvotes: 0
Views: 65
Reputation: 109242
The problem is the transition. It means that the bars/axes aren't removed immediately. However, the code to re-draw everything is run immediately. When that code runs, the bars are still there, selected, the data matched to them, and hence the .enter()
selection is empty.
The easiest way to fix this is to remove the transition, see here. If you want to keep it, you need to stagger the two code blocks, making sure that the second one executes only when everything has been removed. You can use for example the transition.each("end", ...)
event handler for this, but it will make your code a bit more involved. You can also simply use setTimeout()
, see here.
Upvotes: 1