2014-12-07 45 views
1

我有一個更新按鈕,可以將新的.csv數據加載到D3.s堆積條形圖中。我的問題是,在更新它似乎是使用兩個數據集,而不是僅僅是新的。我認爲這與我對update和selectAll有些困惑有關,但我一直無法弄清楚如何替換而不是追加。這裏是我當前的代碼:帶更新按鈕的D3.js將新數據添加到舊數據中,而不是替換舊數據

<!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軸標籤的工作過渡,但仍然是上面用實際條形圖描述的相同問題。

+0

您需要處理更新和退出的選擇,以及。見例如[本教程](http://bost.ocks.org/mike/circles/)。 – 2014-12-07 20:16:45

+0

我讀了你包含的鏈接,並最終找到了更新和退出有用的解釋:[鏈接](http://bost.ocks.org/mike/join/),但閱讀它說,處理更新選擇意味着使用.data,我認爲我正在做,並退出它的.enter,我也在更新函數中調用它。很確定我錯過了一些明顯的東西,但是我真的在撓撓我的腦袋,尤其是現在我已經在上面修改後的代碼中正確更新了我的y和x軸。 – hyssop 2014-12-08 17:59:09

+0

您可能需要在'.data()'的第二個參數中提供一個關鍵函數,它告訴D3如何匹配現有數據和傳遞的數據。默認情況下,這是通過索引完成的(即第一個數據與選擇中的第一個元素相匹配,等等),這可能不是你想要的。 – 2014-12-08 18:18:39

回答

1

這是因爲您沒有在更新功能中使用更新和退出連接(請仔細閱讀此文章http://bost.ocks.org/mike/join/)。據我所知,你想更新現有的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)"; }); 
+0

謝謝你的鏈接和建議。我取得了一些進展,但還沒有。我與這個人有同樣的問題:[鏈接](http://stackoverflow.com/questions/18186011/how-to-update-data-in-stack-bar-chart-in-d3)。我的新數據正在更新,但舊數據未被刪除。如果我刪除了enter()。append()行,數據不會更新。如果有幫助,他建立了一個jsfiddle [鏈接](http://jsfiddle.net/9UfT2/2/)。 – hyssop 2014-12-08 17:41:51

相關問題