Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active December 19, 2022 18:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbostock/3e961b4c97a1b543fff2 to your computer and use it in GitHub Desktop.
Save mbostock/3e961b4c97a1b543fff2 to your computer and use it in GitHub Desktop.
Pie Padding
license: gpl-3.0
redirect: https://observablehq.com/@d3/arc-pad-angle

This animation demonstrates the benefit of setting pie.padAngle directly: the relative areas of arcs are preserved. Setting arc.padAngle instead disproportionately affects small arcs, introducing bias.

<!DOCTYPE html>
<meta charset="utf-8">
<canvas width="960" height="500"></canvas>
<script src="//d3js.org/d3.v4.0.0-alpha.4.min.js"></script>
<script>
var data = [1, 1, 2, 3, 5, 8, 13, 21];
var canvas = document.querySelector("canvas"),
context = canvas.getContext("2d");
var width = canvas.width,
height = canvas.height,
outerRadius = height / 2 - 30,
innerRadius = outerRadius / 3;
var arc = d3.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius)
.context(context);
var pie = d3.pie();
var ease = d3.easeCubicInOut,
duration = 2500;
d3.timer(function(elapsed) {
var t = ease(1 - Math.abs((elapsed % duration) / duration - 0.5) * 2),
arcs = pie.padAngle(0.06 * t)(data);
context.save();
context.clearRect(0, 0, width, height);
context.translate(width / 2, height / 2);
context.beginPath();
arcs.forEach(arc.padAngle(0));
context.lineWidth = 1;
context.strokeStyle = "#777";
context.stroke();
context.beginPath();
arcs.forEach(arc.padAngle(0.06 * t));
context.fillStyle = "#ccc";
context.fill();
context.lineWidth = 1.5;
context.lineJoin = "round";
context.strokeStyle = "#000";
context.stroke();
context.restore();
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment