1
我創建了一個基本的例子,以虛擬數據,試圖讓我的周圍添加或在D3的圖形刪除數據時發生了什麼頭。示例小提琴可以看到here。不加D3.js酒吧元素動態
據我瞭解,在generateBars內(數據)功能;
我更新x和y域,確保到軸的下一次調用使他們正確縮放:
var bars = svg.selectAll(".testUpdateBar").data(data);
更新:
testUpdateX.domain(data.map(function(d) {return d.destination;}));
testUpdateY.domain([0, d3.max(data, function(d) {return d.p_in;})]);
從參數傳遞新的數據變量當前酒吧的x,y,寬度和高度:
bars.transition().duration(2500)
.attr("x", function(d) {return testUpdateX(d.destination);})
.attr("y", function(d) {return testUpdateY(d.p_in);})
.attr("width", testUpdateX.bandwidth() - 5)
.attr("height", function(d) {return testUpdateHeight - testUpdateY(d.p_in);})
.style("fill", function(d) {
var maxIn = d3.max(data, function(d) {return d.p_in;});
if (d.p_in < maxIn * 0.3) {
return "red";
} else if (d.p_in > maxIn * 0.3 && d.p_in < maxIn * 0.6) {
return "orange";
} else {
return "green";
}
});
然後,將新的「rect」元素添加到通過.enter()
函數的調用和應用相同的屬性和樣式給它的新的數據:
bars.enter().append("rect").attr("class", "testUpdateBar")
.attr("x", //...)
.attr("y", //...)
etc...
調用.exit()
和.remove()
,以消除已刪除的任何數據吧:
bars.exit().transition().duration(2500).remove();
最後,重新調用我的軸,以便根據新指定的域更新它們:
svg.select(".testUpdateXaxis").transition().duration(2500).call(testUpdateXaxis);
svg.select(".testUpdateYaxis").transition().duration(2500).call(testUpdateYaxis);
爲什麼'Spar'的最終欄不顯示?正確的y軸本身就是它的新值,並且創建了一個空格,但是沒有任何矩形元素似乎被追加。
不必要的長變量名稱的道歉。我在一個現有的文件中測試了這個,並且希望確保這些名稱沒有衝突。
所以通過刪除線,'svg.someFunction()'被返回參考SVG的初始實例,其具有存儲在其中的_actual_ SVG元素?更新小提琴轉換:https://jsfiddle.net/TomPlum/mae58joo/8/ – TomPlum
是的,這是正確的:因爲你以前定義'var svg = d3.select(「body」)。append(「svg」)'你的'var svg'引用附加的SVG。順便說一句,你可以用一個簡單的'merge()'來節省很多代碼:https://jsfiddle.net/fv8ypv4s/ –
我已經看過D3 API中的merge() ://github.com/d3/d3-array/blob/master/README.md#merge)。我假設它將新數據與舊數據合併,即使只傳遞一個參數? – TomPlum