2016-08-12 79 views
2

我創建一個div容器,然後我用svg替換舊的內容D3

var someContainer = d3.select("#abc") 
     .append("div") 
     .classed("svg-container", true) 
     .append("svg") 
     .attr("preserveAspectRatio", "xMinYMin meet") 
     .attr("viewBox","0 0 400 100") 
     .classed("svg-content-responsive", true) 
     .selectAll("circle") 
     .data(someScale.range()); 

我填寫,然後我的數據追加到它

someContainer.remove(); 

someContainer.enter() 
     .append("circle") 
     .attr("x", function (d, i) { 
      return i * 2; 
     }) 
     .attr("y", 5) 
     .attr("height", 15) 
     ....; 

但是,每當我更新的內容svg,即追加新的圈子,全新的div-containersvg-container被創建。這讓我看到舊數據在視覺上保持原位並在底部(即,進一步向下100px)存在新數據。它基本上是一個可視化副本,但有了新的數據......每當我使用我的數據時,一個新的co gets被替換爲舊數據,留下了n個圖形。

以下是css,它對相對容器進行樣式設置,並確保它在窗口大小發生更改時進行縮放。來源:Resize svg when window is resized in d3.js */

.svg-container { 
    display: inline-block; 
    position: relative; 
    width: 100%; 
    padding-bottom: 50%; /* aspect ratio */ 
    vertical-align: top; 
    overflow: hidden; 
} 

.svg-content-responsive { 
    display: inline-block; 
    position: absolute; 
    top: 10px; 
    left: 0; 
} 

任何想法我做錯了什麼?

回答

0

的問題是,每次數據得到更新,一個新的div被創建。

var someContainer = d3.select("#abc") 
    .append("div") 
    .classed("svg-container", true) 
    ... 

爲了更新數據,所述div需要更換,而不是創建新div每次數據更改。 可以通過加入這一行

d3.select(".svg-container").remove(); 

var someContainer = d3.select...

2

如果你只需要刪除所有的舊圈子,你可以如下做到這一點:

someContainer.selectAll("circle").remove() 

然後通過數據添加新的社交圈 - >輸入 - >附加序列。

someContainer.selectAll("circle") 
     .data(new_circle_data) 
     .enter() 
     .append("circle") 
     .attr("x", function (d, i) { 
      return i * 2; 
     }) 
     .attr("y", 5) 
     .attr("height", 15) 
     ....; 

如果你只是想刪除一些現有的圈子,並保持其他人可以使用general update pattern.你需要做這樣的事情:

var circleUpdate = someContainer.selectAll("circle") 
    .data(new_circle_data) 

circleUpdate.enter().append("circle") 
    .attr("x", function (d, i) { 
      return i * 2; 
     }) 
    .attr("y", 5) 
    .attr("height", 15) 
    ....; 

circleUpdate.exit().remove() 
+0

都能跟得上以上,不這樣的伎倆來完成。東西仍然重複。我認爲問題在於每次創建新的** div **時......當使用元素檢查器時,我可以看到每次更新數據時都有一個新的div容器。 – Stophface

+0

僅在創建SVG時纔會創建一次你初始化情節。當您與情節交互以更改它時調用更新功能。這個更新函數只能包含我提供的代碼塊,它應該足以更新這些圓圈。 –