Yet Another EUE Example

http://stackoverflow.com/questions/21683416/d3-js-data-update-remembers-old-data

by Nivaldo

HTML

<svg></svg>

JavaScript

var svg = d3.select("svg");

var BarChart = function BarChart( chart_attributes ){
  // hide variables within function scope
  var chart = {},
      data;

  // data setter and getter
  chart.data = function( new_data ){
    if( new_data ){ data = new_data;}
    //console.log(data);
    return data; 
  };
  
  console.log(chart.data)
  
  // update data and redraw chart
  chart.update = function( new_data ){
    // update data
    if( !new_data ){ console.log("chart.update() - no data set!"); } 
    else{ chart.data( new_data ); }    
     
    // redraw
    var bar_attr = chart_attributes.bars; 
    console.log("oops") 
    var groups = svg.selectAll("g")
        .data( chart.data(), function(d,i){ console.log(d); return d.NAME } ); 
    
    //console.log(chart.data())
    
    var g = groups.enter().append("g");
      
     /*
     The problem is that you're not updating the positions of the bars for updated data. The code that sets the position of the g elements is only run on new data:
     
var g = groups.enter()
  .append("g")
    .attr("transform", function(d, i) { return "translate(100," + ((i * bar_attr.height)+100) + ")"; });
Replacing this with

var g = groups.enter()
  .append("g");
//groups is the update selection; groups.enter() the enter selection and groups.exit() the exit selection
groups.attr("transform", function(d, i) { return "translate(100," + ((i * bar_attr.height)+100) + ")"; });

fixes the problem -- the position is set for the all new and existing g elements now. Complete example here.
     */
    
    groups
       .attr("transform", function(d, i) { return "translate(100," + ((i * bar_attr.height)+100) + ")"; });
    
    var bars = g.append("rect")
      .attr("x", bar_attr.x)
      .attr("height", bar_attr.height-1).transition()
    .attr("width", function(d,i){return d.INTENSITY*10} );
    
    g.append("text")
      .attr("y", bar_attr.height-2 )
      .attr("x", 0)
      .attr("font-size", bar_attr.height )
      .text(...