我想在這裏做一些修改。首先,將rect
和text
換成g,所以你只需要一次數據綁定。然後,你可以自由地轉換他們一起:
var uSel = svg.selectAll(".input")
.data(dataset); //<-- selection of gs
uSel.exit().remove(); //<-- anybody leaving? remove g (both rect and text)
var gs = uSel
.enter()
.append("g")
.attr("class", "input"); //<-- enter selection, append g
gs.append("rect")
.attr("fill", "rgb(250, 128, 114)"); //<-- enter selection, rect to g
gs.append("text")
.attr("class", "percentage-label")
.style("fill", "white")
.attr("x", function(d, i) {
return i * (w/dataset.length) + 2.5/100 * w + w * 10/100;
}); //<-- enter selection, text to g
uSel.select("rect")
.attr("x", function(d, i) {
return i * (w/dataset.length) + 2.5/100 * w;
})
.attr("width", w/dataset.length - barPadding)
.attr("height", y(0))
.transition().duration(1750).ease("linear")
.attr("y", function(d) {
return y(d);
})
.attr("height", function(d) {
return h - y(d);
}); //<-- update rects with transition
uSel.select("text")
.transition().duration(1750).ease("linear")
.attr("y", function(d) {
return y(d);
})
.text(function(d) {
return d + "%";
}); //<-- update text with transition
更新fiddle。
編輯
過渡的文字,你可能將不得不使用custom tween function:
uSel.select("text")
.transition().duration(1750).ease("linear")
.attr("y", function(d) {
return y(d); //<-- move the text
})
.tween("", function(d) {
var self = d3.select(this),
oldValue = y.invert(self.attr("y")), //<-- get the current value
i = d3.interpolateRound(oldValue, d); //<-- interpolate to new value
return function(t) {
self.text(i(t) + '%') <-- update the text on each iteration
};
});
更新,更新fiddle。
謝謝!好的解決方案我更接近我想達到的目標。 –
但我希望標籤顯示其當前高度的值。現在它顯示了它將轉換到的值。我希望它像一個櫃檯。計算從一個轉換點到另一個轉換點的所有數字。抱歉。我沒有足夠清楚地表達自己 –
@AndreasDominguez,看到更新的答案。 – Mark