How to update d3.js bar chart with new data

后端 未结 2 1920
有刺的猬
有刺的猬 2020-12-06 05:54

I’ve started with the “Let’s make a bar chart I” example here: http://bost.ocks.org/mike/bar/

And I’m having a hard time figuring out how to make the very simple bar

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-06 06:34

    Accepted answer was answered before d3 version 4 released, but if you use d3v4 you have to make update another way because of (excerpt from changelog):

    selection.append no longer merges entering nodes into the update selection; use selection.merge to combine enter and update after a data join.

    // enter and update selection
    bars
      .enter()
      .append("div")
      .merge(bars) // <== !!!
      .style("width", function (d) {return scale(d) + "%";})
      .text(function (d) {return d;});
    
    
    // exit selection
    bars
      .exit().remove();
    

    Working example in hidden snippet below:

    function draw(data) {
        var scale = d3.scaleLinear()
            .domain([0, 50])
            .range([0, 100]);
    
        var bars = d3.select("#work_queues_chart")
            .selectAll("div")
            .attr("id","work_queues_chart")
            .data(data);
         
        // enter and update selection
        bars
          .enter().append("div")
          .merge(bars)
          .style("width", function (d) {return scale(d) + "%";})
          .text(function (d) {return d;});
    
        
        // exit selection
        bars
            .exit().remove();
    };
    
    function update() {
        var data = [4, 8, 15, 16, 23, 42];
        draw(data);
    };
    
    var data = [10, 10, 10, 10, 10, 10];
    window.onload = draw(data);
    
    d3.select('#update')
        .on("click",update);
    #work_queues_chart div {
        font-size: 0.5em;
        font-family: sans-serif;
        color: white;
        background-color: steelblue;
        text-align: right;
        padding: 0.5em;
        margin: 0.2em;
    }

提交回复
热议问题