JSFiddle - React, Tailwind, and code Playground
by James
HTML
<form>
<label>
<input type="radio" name="dataset" id="smith" value="smith" checked>Smith</label>
<label>
<input type="radio" name="dataset" id="jones" value="jones">Jones</label>
</form>
<script src="http://d3js.org/d3.v3.min.js"></script>
CSS
body {
font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;
margin: auto;
position: relative;
width: 960px;
}
text {
font: 10px sans-serif;
}
form {
position: absolute;
right: 10px;
top: 10px;
}
JavaScript
var data = [{
"feeling": "Strongly disagrees",
"jones": "4",
"smith": "22"
}, {
"feeling": "Disagrees",
"jones": "8",
"smith": "22"
}, {
"feeling": "Agrees",
"jones": "50",
"smith": "0"
}, {
"feeling": "Strongly agrees",
"jones": "38",
"smith": "50"
}];
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;
var color = d3.scale.category20();
var pie = d3.layout.pie()
.value(function (d) {
theData;
})
.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 + ")");
d3.selectAll("input").on("change",
function change() {
var theData;
var value = this.value === "pie" ? theData = function (d) {
return d.jones;
} : theData = function (d) {
return d.smith;
}
return theData;
});
function update() {
var path = svg.datum(data).selectAll("path")
.data(pie)
.enter().append("path")
.attr("fill", function (d, i) {
return color(i);
})
.attr("d", arc)
.each(function (d) {
this._current = d;
}); // store the initial angles
var timeout = setTimeout(function () {
d3.select("input[value=\"oranges\"]").property("checked", true).each(change);
}, 2000);
function change() {
var value = this.value;
clearTimeout(timeout);
pie.value(function (d) {
return d[value];
}); // change the value function
path = path.data(pie); // compute the new angles
path.transition().duration(750).attrTween("d", arcTween); // redraw the arcs
}
};
// Store the displayed angles in _current.
// Then, interpolate from _current to the new angles.
// During the transition, _current is updated in-place by...