D3 - Update bar chart data onclick

前端 未结 2 1941
南旧
南旧 2021-01-22 13:22

I am trying to update my web page content when the user clicks on a button using D3. Unfortunately I can see that onclick new data is being displayed, but the old data is not fo

相关标签:
2条回答
  • You need to select the elements that actually exist and do that only once:

    var sel = svg.selectAll("rect")
                 .data(data);
    
    sel.exit().remove();
    sel.enter().append("rect")
    // etc
    
    0 讨论(0)
  • 2021-01-22 14:00

    Maybe this tutoial helps: Thinking with Joins.

    You need to update them, not just remove/add the difference between new/old data.

    var bars = svg.selectAll('bar')
        .data(data);
    
    // Remove
    bars.exit().remove();
    // Add
    bars.enter().append('rect').style('fill', 'orange');
    
    // Update 
    bars.attr('x', function(d) { return x(d.date); })
        .attr('width', x.rangeBand())
        .attr('y', function(d) { return y(d.value); })
        .attr("height", function(d) { return height - y(d.value); }); 
    
    0 讨论(0)
提交回复
热议问题