Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active February 9, 2016 02:04
Show Gist options
  • Save mbostock/5681974 to your computer and use it in GitHub Desktop.
Save mbostock/5681974 to your computer and use it in GitHub Desktop.
Pie Chart Update, IV
license: gpl-3.0
region fruit count
East Apples 53245
West Apples 28479
South Apples 19697
North Apples 24037
Central Apples 40245
East Oranges 200
South Oranges 200
Central Oranges 200
<!DOCTYPE html>
<meta charset="utf-8">
<style>
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;
}
input {
margin: 0 7px;
}
</style>
<form></form>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;
var color = d3.scale.category20();
var pie = d3.layout.pie()
.value(function(d) { return d.count; })
.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");
d3.tsv("data.tsv", type, function(error, data) {
var regionsByFruit = d3.nest()
.key(function(d) { return d.fruit; })
.entries(data);
var label = d3.select("form").selectAll("label")
.data(regionsByFruit)
.enter().append("label");
label.append("input")
.attr("type", "radio")
.attr("name", "fruit")
.attr("value", function(d) { return d.key; })
.on("change", change)
.filter(function(d, i) { return !i; })
.each(change)
.property("checked", true);
label.append("span")
.text(function(d) { return d.key; });
function change(region) {
path = path.data(pie(region.values), function(d) { return d.data.region; });
path.enter().append("path").attr("fill", function(d) { return color(d.data.region); });
path.exit().remove();
path.attr("d", arc);
}
});
function type(d) {
d.count = +d.count;
return d;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment