object consistency in D3 pies
demonstrating how object consistency in pies may or may not work
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.1.6/d3.min.js"></script>
<form>
<input type="button" onClick="add1()" value="add">
<input type="button" onClick="remove1()" value="remove">
</form>
CSS
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
margin: auto;
position: relative;
width: 960px;
}
text {
font: 10px sans-serif;
}
JavaScript
function add1() {
var rAmount = getRandomInt(1000, 50000);
dataset.push(rAmount);
change();
}
function remove1() {
var randomIndex = Math.floor(Math.random() * dataset.length);
console.log('the value removed from the array is: ' + dataset[randomIndex]);
dataset.splice(randomIndex, 1);
change();
}
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var dataset = [53245, 28479, 19697, 24037, 40245];
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;
var enterAntiClockwise = {
startAngle: Math.PI * 2,
endAngle: Math.PI * 2
};
var color = d3.scale.category20();
var pie = d3.layout.pie()
.sort(null);
var arc = d3.svg.arc()
.innerRadius(radius - 100)
.outerRadius(radius - 20);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var path = svg.selectAll("path")
.data(pie(dataset))
.enter().append("path")
.attr("fill", function(d, i) { return color(i); })
.attr("d", arc)
.each(function(d) { this._current = d; }); // store the initial values
function change() {
path = path.data(pie(dataset)); // update the data
// set the start and end angles to Math.PI * 2 so we can transition
// anticlockwise to the actual values later
path.enter().append("path")
.attr("fill", function (d, i) {
return color(i);
})
.attr("d", arc(enterAntiClockwise))
.each(function (d) {
this._current = {
data: d.data,
value: d.value,
startAngle: enterAntiClockwise.startAngle,
endAngle: enterAntiClockwise.endAngle
};
}); // store the initial values
path.exit()
.transition()
.duration(750)
.attrTween('d', arcTweenOut)
.each(function (d) { console.log('D3 is exiting ' + d.data);})
.remove() // now remove the exiting arcs
...