Skip to content

Instantly share code, notes, and snippets.

@adamjanes
Last active April 7, 2018 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamjanes/5e53cfa2ef3d3f05828020315a3ba18c to your computer and use it in GitHub Desktop.
Save adamjanes/5e53cfa2ef3d3f05828020315a3ba18c to your computer and use it in GitHub Desktop.
Pie Chart Update, II (V5)
license: gpl-3.0
{
"apples": [
{ "region": "North", "count": "53245"},
{ "region": "South", "count": "28479"},
{ "region": "East", "count": "19697"},
{ "region": "West", "count": "24037"},
{ "region": "Central", "count": "40245"}
],
"oranges": [
{ "region": "North", "count": "200"},
{ "region": "South", "count": "200"},
{ "region": "East", "count": "200"},
{ "region": "West", "count": "200"},
{ "region": "Central", "count": "200"}
]
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
#chart-area svg {
margin:auto;
display:inherit;
}
text {
font: 10px sans-serif;
}
form {
position: absolute;
right: 10px;
top: 10px;
}
</style>
</head>
<body>
<div id="chart-area">
<form>
<label><input type="radio" name="dataset" value="apples" checked> Apples</label>
<label><input type="radio" name="dataset" value="oranges"> Oranges</label>
</form>
</div>
<script src="//d3js.org/d3.v5.min.js"></script>
<!-- Our JS code -->
<script>
const width = 540;
const height = 540;
const radius = Math.min(width, height) / 2;
const svg = d3.select("#chart-area")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", `translate(${width / 2}, ${height / 2})`);
const color = d3.scaleOrdinal(["#66c2a5","#fc8d62","#8da0cb",
"#e78ac3","#a6d854","#ffd92f"]);
const pie = d3.pie()
.value(d => d.count)
.sort(null);
const arc = d3.arc()
.innerRadius(0)
.outerRadius(radius);
function type(d) {
d.apples = Number(d.apples);
d.oranges = Number(d.oranges);
return d;
}
function arcTween(a) {
const i = d3.interpolate(this._current, a);
this._current = i(1);
return (t) => arc(i(t));
}
d3.json("data.json", type).then(data => {
d3.selectAll("input")
.on("change", update);
function update(val = this.value) {
// Join new data
const path = svg.selectAll("path")
.data(pie(data[val]));
// Update existing arcs
path.transition().duration(200).attrTween("d", arcTween);
// Enter new arcs
path.enter().append("path")
.attr("fill", (d, i) => color(i))
.attr("d", arc)
.attr("stroke", "white")
.attr("stroke-width", "6px")
.each(function(d) { this._current = d; });
}
update("apples");
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment