Accepted answer

The main issue with your script is that the d3 code only executes once. When you have multiple data sets, the d3 pattern (bind, add, update, remove) must be called each time the data is updated.

Here is a rough outline of what will accomplish what you want:

// config, add svg
var canvas ='body')

// function that wraps around the d3 pattern (bind, add, update, remove)
function updateLegend(newData) {

    // bind data
    var appending = canvas.selectAll('rect')

    // add new elements

    // update both new and existing elements
        .attr("width",function (d) {return d.y; });

    // remove old elements


// generate initial legend

// handle on click event'#opts')
  .on('change', function() {
    var newData = eval('value'));

Here is a working fiddle that demonstrates the data changing with a select (probably needs to be tweaked for your needs):

Related Query

More Query from same tag