Why is data not updating correctly on this D3.js barchart?

Sunday, May 4, 2014

I've built a D3.js barchart comparing several years of data. This is a demo.


As per Mike Bostock's Let's Make a Bar Chart tutorials, the structure of bars is as follows, with a rect and a text element (representing the bar and its label respsectively) nested within a g.bar element, and all g.bars being held in g.chart.



<g class="chart" transform="translate(45,10)">
<g class="bar" transform="translate(0,0)">
<rect style="fill: rgb(117, 220, 205); stroke-width: 0.5; stroke: rgb(255, 255, 255);" height="2.0673635307781666" width="56.9547619047619" y="116.5993031358885">
<text class="total" y="111.5993031358885" x="28.47738095238095" text-anchor="middle" alignment-baseline="middle" style="stroke: none; fill: rgb(51, 51, 51); font-size: 0.5em; font-weight: bold; display: none;">60</text>
</g>
<g class="bar" transform="translate(0,0)">
<rect style="fill: rgb(117, 220, 205); stroke-width: 0.5; stroke: rgb(255, 255, 255);" height="2.0673635307781666" width="56.9547619047619" y="116.5993031358885">
<text class="total" y="111.5993031358885" x="28.47738095238095" text-anchor="middle" alignment-baseline="middle" style="stroke: none; fill: rgb(51, 51, 51); font-size: 0.5em; font-weight: bold; display: none;">60</text>
</g>
...
</g>


Each g.bar should only have one rect and one text element nested within it. In testing my chart, I've noticed that some exits don't appear to be occurring properly. You have to reproduce this by inspecting the demo with Firebug or Chrome dev tools, but after changing a year or indeed on loading the chart without changing the year, each g.bar contains more than one rect and text element. Am I not implementing the enter() exit() remove() pattern correctly? How can I fix this? Thanks!







http://ift.tt/1lQ5kBa