pie update
by Nivaldo
HTML
<div id="chart-container" style="width: 460px; height: 460px; border: solid 1px #000;"></div>
<button id="update">Update</button>
CSS
.donut-chart > .slices > .slice:nth-child(1) > .outer > path {
fill: red;
}
.donut-chart > .slices > .slice:nth-child(1) > .inner > path {
fill: darkred;
}
.donut-chart > .slices > .slice:nth-child(2) > .outer > path {
fill: blue;
}
.donut-chart > .slices > .slice:nth-child(2) > .inner > path {
fill: darkblue;
}
.donut-chart > .slices > .slice:nth-child(3) > .outer > path {
fill: green;
}
.donut-chart > .slices > .slice:nth-child(3) > .inner > path {
fill: darkgreen;
}
.donut-chart > .slices > .slice:nth-child(4) > .outer > path {
fill: yellow;
}
.donut-chart > .slices > .slice:nth-child(4) > .inner > path {
fill: orange;
}
JavaScript
// Data
var data1 = [{
label: "One",
value: 33
}, {
label: "Two",
value: 33
}, {
label: "Three",
value: 33
}];
var data2 = [{
label: "One",
value: 20
}, {
label: "Two",
value: 20
}, {
label: "Three",
value: 60
}];
var data3 = [{
label: "One",
value: 20
}, {
label: "Two",
value: 20
}, {
label: "Three",
value: 20
}, {
label: "Four",
value: 40
}];
// Stage Container
var container = d3.select("#chart-container");
var containerHeight = parseInt(container.style("height"));
var containerWidth = parseInt(container.style("width"));
// Stage
var stageSVG = container.append("svg")
.attr("width", containerWidth)
.attr("height", containerHeight)
.attr("class", "donut-chart");
// Pie Layout
var pie = d3.layout.pie()
.sort(null)
.value(function (d) {
return d.value;
});
// Pie Slice Arcs
var pieRadius1 = Math.round(containerHeight / 2);
var pieRadius2 = pieRadius1 - 10;
var donutWidth = 80;
var outerArc = d3.svg.arc()
.innerRadius(pieRadius2 - donutWidth)
.outerRadius(pieRadius2);
var innerArc = d3.svg.arc()
.innerRadius(pieRadius2 - donutWidth)
.outerRadius(pieRadius2 - (donutWidth / 2));
// Slices Container
var slicesGroup = stageSVG.append("g")
.attr("class", "slices")
.attr("transform", "translate(" + pieRadius1 + ", " + pieRadius1 + ")");
//------------------------------------
updateData(data1);
// Change Data
function updateData(dataset) {
console.info(dataset);
// Set Data
var allSlices = slicesGroup.selectAll(".slice")
.data(pie(dataset));
// enter selection
var newSlices = allSlices.enter()
.append("g")
.attr("class", "slice");
// update selection
allSlices.append("g")
.attr("class", "outer")
.append("path")
.attr("d", outerArc);
// update selection
allSlices.append("g")
.attr("class", "inner")
.append("path")
.attr("d",...