D3 How to change dataset based on drop down box selection

后端 未结 1 1924
感动是毒
感动是毒 2021-02-02 18:02

I am trying to update/change the data for rectangles based on drop down box selection. I have tried various things and I don\'t really understand the D3 dispatch function well e

相关标签:
1条回答
  • 2021-02-02 18:55

    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 = d3.select('body')
        .append('svg')
        .attr('width',100)
        .attr('height',100) 
        .appeng('g');
    
    
    // function that wraps around the d3 pattern (bind, add, update, remove)
    function updateLegend(newData) {
    
        // bind data
        var appending = canvas.selectAll('rect')
           .data(newData);
    
        // add new elements
        appending.enter().append('rect');
    
        // update both new and existing elements
        appending.transition()
            .duration(0)
            .attr("width",function (d) {return d.y; });
    
        // remove old elements
        appending.exit().remove();
    
    }
    
    // generate initial legend
    updateLegend(initialValues);
    
    // handle on click event
    d3.select('#opts')
      .on('change', function() {
        var newData = eval(d3.select(this).property('value'));
        updateLegend(newData);
    });
    

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

    http://jsfiddle.net/spanndemic/5JRMt/

    0 讨论(0)
提交回复
热议问题