title: update d3 chart with new data
body: <p>I want to update the bar chart with new data and I looked over this question:
  <a href="https://stackoverflow.com/questions/22052694/how-to-update-d3-js-bar-chart-with-new-data">How to update d3.js bar chart with new data</a>
  But it is not working for me. Probably because I don't know where to put the exit().remove() functions within my code. I tried putting this line </p>
  
  <pre><code>svg.selectAll("rect").exit().remove();
  </code></pre>
  
  <p>below the create bars section but it just removes all of the labels. Then, if I put it right after the create labels portion it removes the chart entirely. How can I get the update button change the chart with new data? </p>
  
  <pre><code>    function draw(data) {
          //Width and height
          var w = 250;
          var h = 250;
  
          var xScale = d3.scale.ordinal()
                          .domain(d3.range(data.length))
                          .rangeRoundBands([0, w], 0.05);
  
          var yScale = d3.scale.linear()
                          .domain([0, d3.max(data)])
                          .range([0, h]);
  
          //Create SVG element
          var svg = d3.select("#chart")
                      .append("svg")
                      .attr("width", w)
                      .attr("height", h);
  
          //Create bars
          svg.selectAll("rect")
             .data(data)
             .enter()
             .append("rect")
             .attr("x", function(d, i) {
                  return xScale(i);
             })
             .attr("y", function(d) {
                  return h - yScale(d);
             })
             .attr("width", xScale.rangeBand())
             .attr("height", function(d) {
                  return yScale(d);
             })
             .attr("fill", "steelblue");
  
          //Create labels
          svg.selectAll("text")
             .data(data)
             .enter()
             .append("text")
             .text(function(d) {
                  return d;
             })
             .attr("text-anchor", "middle")
             .attr("x", function(d, i) {
                  return xScale(i) + xScale.rangeBand() / 2;
             })
             .attr("y", function(d) {
                  return h - yScale(d) + 14;
             })
             .attr("font-family", "sans-serif")
             .attr("font-size", "11px")
             .attr("fill", "white");
  
          };
  
          function update() {
              var data = [ 25, 22, 18, 15, 13 ];
              draw(data);
          }
  
          var data = [ 21, 3, 5, 21, 15 ];
  
          window.onload = draw(data);
  </code></pre>