带有更新按钮的D3.js将新数据添加到旧数据而不是替换旧数据

时间:2014-12-07 18:38:42

标签: javascript d3.js

我有一个更新按钮可以将新的.csv数据加载到D3.s堆积条形图中。我的问题是,在更新时,它似乎使用两个数据集而不仅仅是新数据集。我认为这与我对update和selectAll的一些混淆有关,但我无法弄清楚如何替换而不是追加。这是我目前的代码:

<!DOCTYPE html>
<meta charset="utf-8">
<style>

body {
  font: 10px sans-serif;
}

.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.bar {
  fill: steelblue;
}

.x.axis path {
  display: none;
}

</style>

<body>
<!-- <label><input type="checkbox"> Sort values</label> -->
<div id="option">
    <input name="updateButton" 
           type="button" 
           value="Update" 
           onclick="updateData()" />
</div>

<script src="http://d3js.org/d3.v3.min.js"></script>
<script>

var margin = {top: 20, right: 20, bottom: 200, left: 40},
    width = 960 - margin.left - margin.right,
    height = 650 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
    .rangeRoundBands([0, width], .1);

var y = d3.scale.linear()
    .rangeRound([height, 0]);

var color = d3.scale.ordinal()
    .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .tickFormat(d3.format(".2s"));

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

d3.csv("FinalData4.csv", function(error, data) {
      color.domain(d3.keys(data[0]).filter(function(key) { return key !== "State"; }));

      data.forEach(function(d) {
        var y0 = 0;
        d.ages = color.domain().map(function(name) { return {name: name, y0: y0, y1: y0 += +d[name]}; });
        d.total = d.ages[d.ages.length - 1].y1;
      });

      //data.sort(function(a, b) { return b.total - a.total; });

      x.domain(data.map(function(d) { return d.State; }));
      y.domain([0, d3.max(data, function(d) { return d.total; })]);

    // x-axis label
    svg.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate(0," + height + ")")
            .call(xAxis)
            .selectAll("text")  
                .style("text-anchor", "end")
                .attr("dx", "-.8em")
                .attr("dy", ".15em")
                .attr("transform", function(d) {
                    return "rotate(-65)" 
                    });

    // y-axis label      
      svg.append("g")
          .attr("class", "y axis")
          .call(yAxis)
        .append("text")
          .attr("transform", "rotate(-90)")
          .attr("y", 6)
          .attr("dy", ".71em")
          .style("text-anchor", "end")
          .text("USD in Millions");

    // adds bars
      var state = svg.selectAll(".state")
          .data(data)
        .enter().append("g")
          .attr("class", "g")
          .attr("transform", function(d) { return "translate(" + x(d.State) + ",0)"; });

      state.selectAll("rect")
          .data(function(d) { return d.ages; })
        .enter().append("rect")
          .attr("width", x.rangeBand())
          .attr("y", function(d) { return y(d.y1); })
          .attr("height", function(d) { return y(d.y0) - y(d.y1); })
          .style("fill", function(d) { return color(d.name); });

    // set up the legend
      var legend = svg.selectAll(".legend")
          .data(color.domain().slice().reverse())
        .enter().append("g")
          .attr("class", "legend")
          .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

      legend.append("rect")
          .attr("x", width - 18)
          .attr("width", 18)
          .attr("height", 18)
          .style("fill", color);

      legend.append("text")
          .attr("x", width - 24)
          .attr("y", 9)
          .attr("dy", ".35em")
          .style("text-anchor", "end")
          .text(function(d) { return d; });

});

// ** Update data section (Called from the onclick)
function updateData() {


// Get the data again
d3.csv("FinalData2015.csv", function(error, data2) {
      color.domain(d3.keys(data2[0]).filter(function(key) { return key !== "State"; }));

      data2.forEach(function(d) {
        var y0 = 0;
        d.ages = color.domain().map(function(name) { return {name: name, y0: y0, y1: y0 += +d[name]}; });
        d.total = d.ages[d.ages.length - 1].y1;
      });

      x.domain(data2.map(function(d) { return d.State; }));
      y.domain([0, d3.max(data2, function(d) { return d.total; })]);


        var tran = d3.select("body").transition();

        // change x-axis label
        tran.select(".x.axis")
            .duration(1000)
            .call(xAxis)
            .selectAll("text")  
                .style("text-anchor", "end")
                .attr("dx", "-.8em")
                .attr("dy", ".15em")
                .attr("transform", function(d) {
                    return "rotate(-65)" 
                    });

        // change the y-axis label      
        tran.select(".y.axis")
            .duration(1000)
            .call(yAxis);

      // adds bars
      var state = svg.selectAll(".State")
          .data(data2)          
          .enter().append("g")
          //.transition()
          //.duration(1000)
          .attr("class", "g")
          .attr("transform", function(d) { return "translate(" + x(d.State) + ",0)"; });

      var test = state.selectAll("rect")
          .data(function(d) { return d.ages; })
          .enter().append("rect")
          .transition()
          .duration(1000)
          .attr("width", x.rangeBand())
          .attr("y", function(d) { return y(d.y1); })
          .attr("height", function(d) { return y(d.y0) - y(d.y1); })
          .style("fill", function(d) { return color(d.name); });

    });
}
</script>
</body>

更新:我将functionUpdateData()代码更改为我当前的代码,因为我意识到它有一些垃圾。新代码具有x和y轴标签的工作转换,但仍然与上面描述的实际条形码相同。

1 个答案:

答案 0 :(得分:1)

这是因为您没有在更新功能中使用更新和退出连接(请仔细阅读本文http://bost.ocks.org/mike/join/)。据我所知,您希望使用新的csv数据更新现有的csv数据,因为您需要更新当前的数据集。我将举例说明一个更简单的代码:

function updateData() {
    //this is the new data that you are binding to some circles on the canvas
    var circle = svg.selectAll("circle").data([200, 100, 50,10,5]);
    //if there is new data, you get those new circles with the enter() method
    var circleEnter = circle.enter().append("circle");
    circleEnter.attr("cy", 60);
    circleEnter.attr("cx", function(d, i) { return i * 100 + 30; });
    circleEnter.attr("r", function(d) { return Math.sqrt(d); });

    //------THIS IS THE PART YOU ARE MISSING------
    //but the circles that already exist need an update. (check there is no enter() method here)
    circle.attr("r", function(d) { return Math.sqrt(d); });

    //also you need to remove the circles that don´t have a data binding.
    circle.exit().remove();
}

所以我认为在你的代码中你必须写一些类似的东西:

var state = svg.selectAll(".state").data(data);

//the update data
state.attr("transform", function(d) { return "translate(" + x(d.State) + ",0)"; });