Skip to content

Instantly share code, notes, and snippets.

@robert-moore
Last active February 17, 2018 19:54
Show Gist options
  • Save robert-moore/6760c28cbce48bb2a22dc1dbad992be1 to your computer and use it in GitHub Desktop.
Save robert-moore/6760c28cbce48bb2a22dc1dbad992be1 to your computer and use it in GitHub Desktop.
Pie Chart
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
const color = ['#3E50AF', '#577EE5', '#67AFFA', '#267DB8', '#52A0D4', '#78BDEB'];
const favoriteSports = [
{ sport: "Football", count: 26},
{ sport: "Basketball", count: 17},
{ sport: "Hockey", count: 16},
{ sport: "Underwater Hockey", count: 14},
{ sport: "Chess Boxing", count: 12},
{ sport: "Cheese Rolling", count: 8}
];
const height = 500;
const width = 500;
const radius = Math.min(height, width) / 2;
const svg = d3.select('body').append('svg')
.attr('height', height)
.attr('width', width);
const g = svg.append('g')
.attr('transform', "translate(" + width / 2 + "," + height / 2 + ")");
// calculate the corresponding "start" and "end" angles for our data
const pie = d3.pie()
.sort(null)
.value(function(d) { return d.count; });
// calculate the "d" attribute for our path with d3.arc()
const arc = d3.arc()
.outerRadius(radius - 10)
.innerRadius(0);
const path = g.selectAll("path")
.data(pie(favoriteSports))
.enter()
.append("path")
.attr("d", arc)
.attr("fill", function(d, i) { return color[i]; })
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment